coordinates specification for panels - java

How can I specify the coordinates of the following panel, instead of having it aligned to the center.
I have tried a lot and used different layouts, but still couldn't get it to work. Please help me solving this problem. Thanks!
Here is my code..
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Lesson2 extends JFrame {
private static final long serialVersionUID = -198253288329146091L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Lesson2 frame = new Lesson2();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Lesson2() {
contentPane = new JPanel();
setContentPane(contentPane);
JPanel panel = new JPanel() {
private static final long serialVersionUID = -5974584127539186578L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(0, 0, 500, 500);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
};
contentPane.add(panel);
}
}
Here is an example of how it looks now
https://prnt.sc/moe3al
Here is the final code edited using a nulled layout with a set size
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Lesson1 extends JFrame {
private static final long serialVersionUID = -198253288329146091L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Lesson1 frame = new Lesson1();
frame.setSize(1000, 1000);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Lesson1() {
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel() {
private static final long serialVersionUID = -5974584127539186578L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(0, 0, 500, 500);
}
};
panel.setLayout(null);
panel.setSize(500, 500);
contentPane.add(panel);
}
}

All Swing/AWT containers use FlowLayout as the default layout manager, which results in the component being centered. If you want more control, you can use Absolute Positioning by calling contentPane.setLayout(null) and setting the component's coordinates via panel.setBounds(), but be aware that it may not handle window resize elegantly.

Related

Can graphics.drawString change it properties outside paintComponent?

I'm trying to change the style of the string based on the status of two check boxes. One is boldCheck and the other is italicCheck. However when I run the program it draws the default string in the paintComponent and the two checkboxes are not working? and there is actual problems in the code itself but the problem seems the way I made this code. Any help on fixing this issue will be much appreciated.
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class JavaTest {
public static void main(String[] args) {
JFrame window = new JFrame("HomeWork");
DrawMessage message = new DrawMessage();
window.add(message);
window.setVisible(true);
window.setSize(600,300);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
static class DrawMessage extends JPanel{
private static final JCheckBox boldCheck = new JCheckBox("Bold");
private static final JCheckBox italicCheck = new JCheckBox("Italic");
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(new Font("TimesRoman", Font.PLAIN, 20));
g.setColor(Color.blue);
g.drawString("Welcome to java Programing", 40, 40);
setBackground(Color.yellow);
add(boldCheck);
add(italicCheck);
CheckBoxHandler handler = new CheckBoxHandler();
boldCheck.addItemListener(handler);
italicCheck.addItemListener(handler);
}
static private class CheckBoxHandler extends DrawMessage implements ItemListener{
private int valBold = Font.PLAIN;
private int valItalic = Font.PLAIN;
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getSource() == boldCheck){
valBold = boldCheck.isSelected() ? Font.BOLD: Font.PLAIN;
}
if(e.getSource() == italicCheck){
valItalic = italicCheck.isSelected() ? Font.ITALIC : Font.PLAIN;
}
DrawMessage obj = new DrawMessage();
obj.setFont(new Font("TimesRoman", valBold + valItalic, 20));
}
}
}
}
I believe the following code achieves what you desire.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class BoldItal extends JPanel implements ItemListener, Runnable {
private JCheckBox boldCheckBox;
private JCheckBox italicCheckBox;
private JFrame frame;
public BoldItal() {
setPreferredSize(new Dimension(600, 300));
setBackground(Color.yellow);
}
#Override
public void run() {
showGui();
}
#Override
public void itemStateChanged(ItemEvent e) {
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int style;
if (boldCheckBox.isSelected()) {
style = Font.BOLD;
if (italicCheckBox.isSelected()) {
style += Font.ITALIC;
}
}
else {
if (italicCheckBox.isSelected()) {
style = Font.ITALIC;
}
else {
style = Font.PLAIN;
}
}
g.setFont(new Font("TimesRoman", style, 20));
g.setColor(Color.blue);
g.drawString("Welcome to java Programing", 40, 40);
}
private JPanel createCheckBoxes() {
JPanel checkBoxesPanel = new JPanel();
boldCheckBox = new JCheckBox("Bold");
boldCheckBox.addItemListener(this);
italicCheckBox = new JCheckBox("Italic");
italicCheckBox.addItemListener(this);
checkBoxesPanel.add(boldCheckBox);
checkBoxesPanel.add(italicCheckBox);
return checkBoxesPanel;
}
private void showGui() {
frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createCheckBoxes(), BorderLayout.PAGE_START);
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new BoldItal());
}
}
You want a repaint to occur whenever you change the selection in one of the check boxes. Hence you add an ItemListener to each check box. Then, in method paintComponent() you set the Font style according to the values of the two check boxes.
You don't change the background color, hence no need to set it in method paintComponent(). Just set it once. I chose to set it in the class constructor, but that is not mandatory. It can also be set, for example, in method showGui().
I made a few changes to your code.
I started the application with a call to the SwingUtilities invokeLater method. This method ensures that the Swing comp[onents are created and executed on the Event Dispatch Thread.
I created two JPanels, one for the checkbox buttons and one to draw the text. Generally, it's not a good idea to put Swing components on a drawing JPanel.
I made the valBold and valItalic fields global since they're set in the controller class and used in the drawing panel class.
The drawing panel draws the text. Period. The controller class will adjust the global Font fields.
I made the drawing panel class and the item listener class public inner classes.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DrawStringGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new DrawStringGUI());
}
private DrawMessage message;
private JCheckBox boldCheck;
private JCheckBox italicCheck;
private int valBold = Font.PLAIN;
private int valItalic = Font.PLAIN;
#Override
public void run() {
JFrame window = new JFrame("HomeWork");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(createCheckBoxPanel(), BorderLayout.BEFORE_FIRST_LINE);
message = new DrawMessage();
window.add(message, BorderLayout.CENTER);
window.pack();
window.setVisible(true);
}
private JPanel createCheckBoxPanel() {
JPanel panel = new JPanel();
CheckBoxHandler handler = new CheckBoxHandler();
boldCheck = new JCheckBox("Bold");
boldCheck.addItemListener(handler);
panel.add(boldCheck);
italicCheck = new JCheckBox("Italic");
italicCheck.addItemListener(handler);
panel.add(italicCheck);
return panel;
}
private void repaint() {
message.repaint();
}
public class DrawMessage extends JPanel {
private static final long serialVersionUID = 1L;
public DrawMessage() {
this.setBackground(Color.YELLOW);
this.setPreferredSize(new Dimension(350, 100));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int style = valBold | valItalic;
g.setFont(new Font("TimesRoman", style, 20));
g.setColor(Color.BLUE);
g.drawString("Welcome to Java Programing", 40, 40);
}
}
public class CheckBoxHandler implements ItemListener {
#Override
public void itemStateChanged(ItemEvent event) {
if (event.getSource() == boldCheck) {
valBold = boldCheck.isSelected() ? Font.BOLD : Font.PLAIN;
}
if (event.getSource() == italicCheck) {
valItalic = italicCheck.isSelected() ? Font.ITALIC : Font.PLAIN;
}
DrawStringGUI.this.repaint();
}
}
}

Java Swing Painting Issue with JButtons

What I'm trying to do is to create a desktop application using Swing. I need to add a background image to my frame and also add some buttons on some specific locations which should NOT have their content area filled. So, here is what I've done so far;
public class MainGUI extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainGUI window = new MainGUI();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainGUI() {
setUndecorated(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(screenSize);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initialize();
}
private void initialize() {
JPanel mainPanel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
try {
g.drawImage(new ImageIcon(ImageIO.read(new File("a.png"))).getImage(), 0, 0, null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
mainPanel.setLayout(new BorderLayout());
JButton btn1 = new JButton();
btn1 .setAlignmentX(Component.CENTER_ALIGNMENT);
btn1 .setContentAreaFilled(false);
btn1 .setBorder(new EmptyBorder(0, 0, 0, 0));
btn1 .setIcon(new ImageIcon("btn1.png"));
JPanel rightButtonPanel = new JPanel();
rightButtonPanel.setLayout(new BoxLayout(rightButtonPanel, BoxLayout.Y_AXIS));
rightButtonPanel.add(btn1);
mainPanel.add(rightButtonPanel, BorderLayout.EAST);
this.setContentPane(mainPanel);
}
}
When I do this, setContentAreaFilled(false) feature does not work. I suppose it's related to the painting but I'm not sure. Can anyone help me with this please?
So I took your code and modified it.
Primarily:
Added btn1.setOpaque(false);
And added rightButtonPanel.setBackground(Color.GREEN);
Example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class MainGUI extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainGUI window = new MainGUI();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainGUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initialize();
pack();
}
private void initialize() {
JPanel mainPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}
};
mainPanel.setBackground(Color.RED);
mainPanel.setLayout(new BorderLayout());
JButton btn1 = new JButton();
btn1.setAlignmentX(Component.CENTER_ALIGNMENT);
btn1.setContentAreaFilled(false);
btn1.setOpaque(false);
btn1.setBorder(new EmptyBorder(0, 0, 0, 0));
btn1.setText("This is a test");
JPanel rightButtonPanel = new JPanel();
rightButtonPanel.setBackground(Color.GREEN);
rightButtonPanel.setLayout(new BoxLayout(rightButtonPanel, BoxLayout.Y_AXIS));
rightButtonPanel.add(btn1);
mainPanel.add(rightButtonPanel, BorderLayout.EAST);
this.setContentPane(mainPanel);
}
}
This produced
So, it's not the buttons (at least at this point) which are at fault.
So, I changed rightButtonPanel.setBackground(Color.GREEN); to rightButtonPanel.setOpaque(false); and it produced

Tooltip behind modal dialog

How to check these kinds of problem. When i checked the menus i have for a desktop application, some shows proper display of tooltip for close button which should always be at the front. But some are displayed at the back of the modal dialog.
Screenshot of the bug:
I kind of have the same problems as the one who posted this: https://coderanch.com/t/460688/java/Glasspanes-tooltips
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class GlassPaneContent extends JPanel {
GlassPaneContent() {
setSize(200, 50);
ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false);
JButton button = new JButton("A button");
button.setToolTipText("A tooltip");
add(button);
}
}
class GlassPane extends JPanel {
private static final Color BG_COLOR = new Color(0, 0, 0, 96);
private GlassPaneContent content = new GlassPaneContent();
public GlassPane() {
setLayout(null);
setOpaque(false);
add(content);
}
#Override
protected void paintComponent(Graphics g) {
g.setColor(BG_COLOR);
g.fillRect(0, 0, getWidth(), getHeight());
int x = (getWidth() - content.getWidth()) / 2;
int y = (getHeight() - content.getHeight()) / 2;
content.setLocation(x, y);
super.paintComponent(g);
}
}
public class MainWindow extends JFrame {
public MainWindow() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 500);
GlassPane gp = new GlassPane();
getRootPane().setGlassPane(gp);
gp.setVisible(true);
}
public static void main(String[] args) {
new MainWindow().setVisible(true);
}
}
We're using JAVA Swing. Kindly comment below if ever i need to post the codes. Thank you!
Try out this one:
public class MainWindow extends JFrame {
public MainWindow() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 500);
GlassPane gp = new GlassPane();
setContentPane(gp);
this.setVisible(true);
}
public static void main(String[] args) {
new MainWindow();
}
}

Adding a jTextArea to JPanel from within the Panel

So, I am creating a new Canvas (JPanel) class: Canvas canvas = new Canvas(); and then I am calling a method on that class: canvas.addTextBox();
Now, from within this Canvas class, I want to add a new jTextArea to the Canvas. I tried using the code below but it isn't showing up. Not sure what I am doing wrong. Thanks!
class Canvas extends JPanel {
public Canvas() {
this.setOpaque(true);
//this.setBackground(Color.WHITE);
}
public void addTextBox() {
final JTextArea commentTextArea = new JTextArea(10, 10);
commentTextArea.setLineWrap(true);
commentTextArea.setLineWrap(true);
commentTextArea.setWrapStyleWord(true);
commentTextArea.setVisible(true);
}
}
Full Code
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class UMLEditor {
public static void main(String[] args) {
JFrame frame = new UMLWindow();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(30, 30, 1000, 700);
frame.getContentPane().setBackground(Color.white);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class UMLWindow extends JFrame {
Canvas canvas = new Canvas();
private static final long serialVersionUID = 1L;
public UMLWindow() {
addMenus();
}
public void addMenus() {
getContentPane().add(canvas);
JMenuBar menubar = new JMenuBar();
JMenuItem newTextBox = new JMenuItem("New Text Box");
newTextBox.setMnemonic(KeyEvent.VK_E);
newTextBox.setToolTipText("Exit application");
newTextBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
canvas.addTextBox();
}
});
menubar.add(newTextBox);
setJMenuBar(menubar);
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
class Canvas extends JPanel {
public Canvas() {
this.setOpaque(true);
//this.setBackground(Color.WHITE);
}
public void addTextBox() {
final JTextArea commentTextArea = new JTextArea(10, 10);
commentTextArea.setLineWrap(true);
commentTextArea.setLineWrap(true);
commentTextArea.setWrapStyleWord(true);
commentTextArea.setVisible(true);
}
}
The addTextBox method only creates a JTextArea. It never adds it to the JPanel
You will need to add the following line to addTextBox method:
add( commentTextArea );
In case the JFrame which contains your components is already visible on screen when the addTextBox method is called, you need to invalidate the container as well. Simply add
revalidate();
repaint();

rectangular component disappears upon resizing the frame

I have a following code ( trying to learn swing and java). I created a ladder using rectangular components using class and placed on the main frame. Everything works okay but if I resize it even slightly, the ShapeManager object (i.e, the ladder) disappears. I don't know what is going on. Any help please.
GUIMain Class:
package mainProg;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.*;
import java.awt.*;
public class GUIMain {
static JPanel mainPanel;
static JButton[] newButtons;
static ShapeManager newShape;
private static class BtnEvtHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
//System.exit(0);
JOptionPane.showMessageDialog( null, "WELCOME" );
}
}
private static JButton[] createButtons() {
JButton[] buttonArray= new JButton[2];
buttonArray[0]=new JButton("OK");
buttonArray[1]=new JButton("MOVE");
BtnEvtHandler okButtonHandler= new BtnEvtHandler();
( buttonArray[0]).addActionListener(okButtonHandler);
return buttonArray;
}
private static ShapeManager createShape(int x) {
ShapeManager newContent=new ShapeManager(x);
return newContent;
}
private static JPanel mainContainer() {
JPanel mainPanel= new JPanel();
mainPanel.setSize(400, 400);
return mainPanel;
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(false);
JFrame frame = new JFrame(" DB ");
mainPanel= mainContainer();
mainPanel.setLayout(new BorderLayout(10, 10));
newButtons= createButtons();
newShape= createShape(20);
newButtons[0].setHorizontalAlignment(0);
mainPanel.add(newButtons[0],BorderLayout.PAGE_START);
newButtons[1].setHorizontalAlignment(0);
mainPanel.add(newButtons[1],BorderLayout.PAGE_END);
newShape.setPreferredSize(new Dimension(400, 400));
mainPanel.add(newShape, BorderLayout.LINE_END);
frame.setContentPane(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setLocation(500,200);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
ShapeManager Class:
package mainProg;
import javax.swing.JPanel;
import java.awt.*;
#SuppressWarnings("serial")
class ShapeManager extends JPanel {
int rectPos;
ShapeManager(int rectPos) {
setPreferredSize(new Dimension(400,400));
this.rectPos=rectPos;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
while (rectPos<150) {
g.setColor(Color.BLUE);
g.drawRect(rectPos+10, rectPos+10, 100, 10);
g.fillRect(rectPos+10, rectPos+10, 100, 10);
rectPos=rectPos+10;
}
}
}
You never reset rectangle position, so after the first paint it remains above 150. You need to reset it after you exit your while loop.
Try this:
g.setColor(Color.BLUE);
int position = rectPos;
while (position<150) {
position += 10;
g.drawRect(position, position, 100, 10);
g.fillRect(position, position, 100, 10);
}

Categories

Resources