Java&Swing: why the componenet isn't added dynamically? - java

The following is my code.
I think click the button, at least, a Color.CYAN block will be added into MainPanel, but it doesn't.
Could you please tell me how to achieve that? Thanks.
public class TestFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
final TestFrame mainFrame = new TestFrame();
mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainFrame.setVisible(true);
});
}
public TestFrame() throws HeadlessException {
setTitle("Frame");
setSize(new Dimension(1000, 800));
final JPanel mainPanel = new JPanel();
final JButton button = new JButton("Test");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
mainPanel.add(new Unit());
}
});
mainPanel.add(button);
mainPanel.revalidate();
add(mainPanel);
}
class Unit extends JComponent {
public Unit() {
setSize(new Dimension(100, 100));
setBackground(Color.CYAN);
}
#Override
protected void paintComponent(Graphics g) {
final Graphics2D g2D = (Graphics2D) g;
g2D.drawString("Hello World", 10, 10);
}
}
}

Your Unit JComponent is likely being added to mainPanel in the ActionListener and thus the GUI, but it has no preferred size and so per the FlowLayout used by JPanels, it will size to [0, 0]. FlowLayouts (and most layout managers) do not respect a component's size but rather its preferredSize. Also, revalidate() and repaint() need to be called on the container (mainPanel) after Unit has been added so that the layout managers can do their laying out of components and to allow the OS to clear dirty pixels.
To solve this, give it a preferred size, preferably by overriding public Dimension getPreferredSize() but by calling setPreferredSize(...) if you must, and by calling revalidate() and repaint() after adding the component to the container.
Better still, add the component to the container using a CardLayout tutorial, but hide it by also adding an empty JLabel, again using a CardLayout, and then display the hidden component by calling CardLayout.show(...) from within ActionListener.
Side note: don't forget the super method within your painting method:
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // add this ****
final Graphics2D g2D = (Graphics2D) g;
g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2D.setFont(UNIT_FONT);
g2D.drawString("Hello World", textX, textY);
}
else you break the painting chain and may see unwanted artifacts or other problems
e.g.,
import java.awt.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class TestFrame extends JFrame {
private CardLayout cardLayout = new CardLayout();
private JPanel cardPanel = new JPanel(cardLayout);
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
final TestFrame mainFrame = new TestFrame();
mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
});
}
public TestFrame() throws HeadlessException {
setTitle("Frame");
setPreferredSize(new Dimension(1000, 800));
final JPanel mainPanel = new JPanel(new BorderLayout());
final JButton button = new JButton("Test");
button.addActionListener(e -> {
cardLayout.next(cardPanel);
});
JPanel btnPanel = new JPanel();
btnPanel.add(button);
mainPanel.add(btnPanel, BorderLayout.PAGE_END);
mainPanel.add(cardPanel);
add(mainPanel);
cardPanel.add(new JLabel(), "Foo");
cardPanel.add(new Unit(), Unit.class.getCanonicalName());
}
static class Unit extends JPanel {
private static final int PREF_W = 100;
private static final int PREF_H = 100;
private static final Font UNIT_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 60);
public Unit() {
setBackground(Color.CYAN);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
final Graphics2D g2D = (Graphics2D) g;
g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2D.setFont(UNIT_FONT);
g2D.drawString("Hello World", 360, 350);
}
}
}

Related

Issue when adding two JPanels

I'm trying to add two JPanels to a JFrame, one with a simple backround and another one with buttons etc. Either I get only buttons or only the background. I can't find a solution to my problem anywhere, so any help would be appreciated. I'm still new to Java, so please don't hate.
GuiMainMenu:
public class GuiMainMenu extends JFrame implements ActionListener, KeyListener {
private static final long serialVersionUID = -7936366600070922227L;
Color blue = new Color(114, 137, 218);
Color gray = new Color(44, 47, 51);
Color white = new Color(255, 255, 255);
ImagePanel panel = new ImagePanel(new ImageIcon("image.png").getImage());
public static int width;
public static int height;
JPanel p = new JPanel();
JPanel p1 = new JPanel();
JLabel l = new JLabel();
JLabel l1 = new JLabel();
JLabel l2 = new JLabel();
JButton b = new JButton();
JButton b1 = new JButton();
JButton b2 = new JButton();
String title = "-";
public GuiMainMenu() {
setSize(m.X, m.Y);
setTitle(title);
setResizable(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
p.setLayout(null);
width = getWidth();
height = getHeight();
getRootPane().addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
width = getWidth();
height = getHeight();
addButtons();
addLabels();
}
});
addLabels();
addButtons();
add(p);
add(panel);
setVisible(true);
}
public void addLabels() {
l.setSize(width, height);
l.setLocation(5, -40);
l.setText("x");
l.setHorizontalAlignment(SwingConstants.LEFT);
l.setVerticalAlignment(SwingConstants.BOTTOM);
l.setForeground(blue);
l.setFont(new Font("Trebuchet MS", Font.PLAIN, 15));
l1.setSize(width, height);
l1.setLocation(-22, -40);
l1.setText("y");
l1.setHorizontalAlignment(SwingConstants.RIGHT);
l1.setVerticalAlignment(SwingConstants.BOTTOM);
l1.setForeground(blue);
l1.setFont(new Font("Trebuchet MS", Font.PLAIN, 15));
l2.setText("test label");
l2.setSize(width, height);
l2.setLocation(0, -75);
l2.setVerticalAlignment(SwingConstants.CENTER);
l2.setHorizontalAlignment(SwingConstants.CENTER);
l2.setForeground(blue);
l2.setFont(new Font("Trebuchet MS", Font.BOLD, 26));
p.add(l);
p.add(l1);
p.add(l2);
validate();
}
public void addButtons() {
b.setText("button0");
b.setFocusable(false);
b.setBorder(null);
b.setLocation(width / 2 - 200, height / 2 - 35);
b.setSize(400, 35);
b.setForeground(white);
b.setBackground(blue);
b.addActionListener(this);
b1.setText("button1");
b1.setFocusable(false);
b1.setBorder(null);
b1.setLocation(width / 2 - 200, height / 2 + 10);
b1.setSize(400, 35);
b1.setForeground(white);
b1.setBackground(blue);
b1.addActionListener(this);
p.add(b);
p.add(b1);
validate();
}
#Override
public void actionPerformed(ActionEvent arg0) {
}
#Override
public void keyPressed(KeyEvent arg0) {
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
ImagePanel Class:
class ImagePanel extends JPanel {
private static final long serialVersionUID = -7270956677693528549L;
private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, GuiMainMenu.width, GuiMainMenu.height, null);
}
}
p.setLayout(null);
Don't use a null layout. Swing was designed to be used with layout managers.
Read the section from the Swing tutorial on Layout Managers for more information and working examples.
Either I get only buttons or only the background
add(p);
add(panel);
The default layout manager for a JFrame is the BorderLayout. If you don't specify a constraint both components get added to the CENTER. However only the last one added will be displayed.
Try the following to see the difference:
add(p, BorderLayout.PAGE_STRT);
add(panel, BorderLayout.CENTER);
one with a simple backround and another one with buttons etc.
However above is not what you want. Swing components have a parent/child relationship. So what you really need is:
backgroundPanel.add(buttonPanel);
add(backgroundPanel, BorderLayout.CENTER);
Note I used more meaningful names because "p" and "panel" and not descriptive. Use descriptive names for variable so people can understand what they mean.
I suppose you want to display a JFrame with a background image and various components. I think after reviewing your code that there is some misunderstanding on your part causing the problem.
I've created a short snippet of code that does the basics and maybe helps you to solve your problem. (Not tested!)
#SuppressWarnings("serial")
public class GuiMainMenu extends JFrame{
private BufferedImage imageBackground; // TODO: load your background image
public GuiMainMenu(){
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(1024, 768));
setMinimumSize(new Dimension(800, 600));
// TODO: setLayout if needed
JPanel panel = (JPanel)add(new JPanel(){
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(imageBackground, 0, 0, this);
}
});
addOtherComponents(panel);
pack();
setLocationRelativeTo(null);
setTitle("Your Title her");
setVisible(true);
}
private void addOtherComponents(JPanel panel){
//TODO: add the needed Stuff
//panel.add ...
}
}

My custom component cannot be painted

I'm trying to create a class(called Stock) which can be identified as a Component--and let me use Listener on it.
However, it is not painted unless you specify (not a good idea!) to paint it in panel.paint().
The program runs as this:
JFrame frame = new JFrame ("..");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
final Stock theStock=new Stock();
JPanel primary = new JPanel();
primary.setPreferredSize(new Dimension(500,500));
primary.add(theStock);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
The Stock will not be painted unless primary(JPanel) is overriden so that there is a specification calling the stock to draw:
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.black);
g.drawRect(x-2, y-2, 74, 124);
}
Here's my code--I guess the problem may happen because I did not override anything else than paint method inherited from Component.
**********Modified to be testable, please see below**
import java.awt.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class Stock extends Component{
private int x; //the position for image
private int y;//position for image
public Stock() {
x=285;
y=280;
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.black);
g.drawRect(x-2, y-2, 74, 124);
}
public void works(){
JFrame frame = new JFrame ("..");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
final Stock theStock=new Stock();
JPanel primary = new JPanel(){
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
theStock.paint(g);
}
};
primary.setPreferredSize(new Dimension(500,500));
primary.add(theStock);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
public void doesNotWork(){
JFrame frame = new JFrame ("..");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
final Stock theStock=new Stock();
JPanel primary = new JPanel();
primary.setPreferredSize(new Dimension(500,500));
primary.add(theStock);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
Stock a = new Stock();
a.works();
//a.doesNotWork();
}
}
p.s.1. I'm not using JComponent because JComponent has more functionalities than I need to use. Component, as from which Container and Button inherit, should work well.
p.s.2. Even you use JComponent you get the same result. Code below.
import java.awt.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class Stock extends JComponent{
private int x; //the position for image
private int y;//position for image
public Stock() {
x=285;
y=280;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawRect(x-2, y-2, 74, 124);
}
public void works(){
JFrame frame = new JFrame ("..");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
final Stock theStock=new Stock();
JPanel primary = new JPanel(){
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
theStock.paint(g);
}
};
primary.setPreferredSize(new Dimension(500,500));
primary.add(theStock);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
public void doesNotWork(){
JFrame frame = new JFrame ("..");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
final Stock theStock=new Stock();
JPanel primary = new JPanel();
primary.setPreferredSize(new Dimension(500,500));
primary.add(theStock);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
Stock a = new Stock();
//a.works();
a.doesNotWork();
}
}
Your problem is one of layouts, size and preferredSize. Since you're adding a your Stock Component to a FlowLayout using JPanel, the Component will size itself at its preferred size which is 0, 0. If you gave the JPanel a different layout, say
primary.setLayout(new BorderLayout());
and then added your Stock object, it would fill the primary JPanel and it would paint itself.
Other options include setting your Stock objects preferredSize, or even overriding its getPreferredSize() method so that it's large enough:
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}

Why is my JPanel messing with other components on my JFrame?

So I have a JFrame which contains a JPanel that holds a JList component.
Then I have another JPanel for my paintComponent() which also returns a dimension.
But when I set the size for the dimension, it tries to relocate my other JPanel.
Here is my code for the paintComponent():
class drawOnPanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.BLUE);
}
#Override
public Dimension getPreferredSize(){
return new Dimension(250, 250);
}
}
Then I have my JFrame which calls the drawOnPanel class:
public static void mainFrame() {
JFrame f = new MTGSAMPServerReference();
f.setTitle("MTG SAMP Server Reference Guide");
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new drawOnPanel());
f.setSize(330, 300);
f.setLocationRelativeTo(null);
}
And then I have my JList which is on my JPanel:
public void MainMenu() {
JPanel controls = new JPanel(new BorderLayout(5,5));
final CardLayout cl = new CardLayout();
final JPanel panel = new JPanel(cl);
controls.add(panel);
this.getContentPane().setLayout(new FlowLayout(FlowLayout.LEADING));
list = new JList<Object>(mainMenu);
list.setVisibleRowCount(7);
select = new JButton("Select");
exit = new JButton("Exit");
select.addActionListener(this);
exit.addActionListener(this);
controls.add(new JScrollPane(list));
JPanel basePanel = new JPanel(new GridLayout(0, 1));
basePanel.add(select);
basePanel.add(exit);
controls.add(basePanel, BorderLayout.PAGE_END);
add(controls);
refreshFrame();
}
When I try to draw on my paintComponent() JPanel, it draws, but the coordinates that I indicate are not correctly drawn.
Does anyone know why this is happening?
Thanks in advance!
EDIT: Here are some screenshots of my program.
This one is what my program looks like when I don't include drawOnPanel:
And this one is what my program looks like when I include drawOnPanel:
I just want it to draw on the right side of the JList, without moving the JList. As you can see, it adjusts the other JPanel.
Any and all help is appreciated!
EDIT: Here is my SSCCE.
EDIT: Here is my SSCCE code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public final class SSCCE1 extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JList list;
JButton select;
JButton exit;
Object[]mainMenu = {"Value 1", "Value 2", "Value 3", "Value 4"};
public SSCCE1() {
MainMenu();
}
public void MainMenu() {
JPanel controls = new JPanel(new BorderLayout(5,5));
final CardLayout cl = new CardLayout();
final JPanel panel = new JPanel(cl);
controls.add(panel);
this.getContentPane().setLayout(new FlowLayout(FlowLayout.LEADING));
list = new JList<Object>(mainMenu);
list.setVisibleRowCount(7);
select = new JButton("Select");
exit = new JButton("Exit");
controls.add(new JScrollPane(list));
JPanel basePanel = new JPanel(new GridLayout(0, 1));
basePanel.add(select);
basePanel.add(exit);
controls.add(basePanel, BorderLayout.PAGE_END);
add(controls);
revalidate();
repaint();
SSCCE1.this.repaint();
}
public void createAndShowGUI() {
mainFrame();
SSCCE1.this.repaint();
}
public static void mainFrame() {
JFrame f = new SSCCE1();
f.setTitle("My SSCCE");
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new drawOnPanel()); // When this is uncommented, it messes with the other JPanel, but when commented, it works fine, but does not allow drawing on the other JFrame.
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
f.setLocationRelativeTo(null);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
SSCCE1 gui = new SSCCE1();
gui.createAndShowGUI();
}
});
}
#Override
public void actionPerformed(ActionEvent ae) {
}
}
class drawOnPanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.BLUE);
}
#Override
public Dimension getPreferredSize(){
return new Dimension(250, 250);
}
}
Make setVisible() last, after a adding, packing and locating. Complete examples are seen here and here.
f.add(…);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
Addendum: Here's a variation on your example, without the invisible panel. Absent a compelling reason to extend JFrame, just create one and add your components.
import java.awt.*;
import javax.swing.*;
/** #see https://stackoverflow.com/a/18038765/230513 */
public class SSCCE2 {
private JList list;
private JButton select;
private JButton exit;
private Object[] mainMenu = {"Value 1", "Value 2", "Value 3", "Value 4"};
public JPanel mainMenu() {
JPanel controls = new JPanel(new BorderLayout(5, 5));
list = new JList(mainMenu);
list.setVisibleRowCount(7);
select = new JButton("Select");
exit = new JButton("Exit");
controls.add(new JScrollPane(list));
JPanel basePanel = new JPanel(new GridLayout(0, 1));
basePanel.add(select);
basePanel.add(exit);
controls.add(basePanel, BorderLayout.PAGE_END);
return controls;
}
public void createAndShowGUI() {
JFrame f = new JFrame("My SSCCE");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new DrawOnPanel());
f.add(mainMenu(), BorderLayout.WEST);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
SSCCE2 gui = new SSCCE2();
gui.createAndShowGUI();
}
});
}
private static class DrawOnPanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(0, 0, getWidth(), getHeight());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(250, 250);
}
}
}

Drawing rectangles on a JPanel

I have a JScrollPane and on top of it I have a JPanel named 'panel1'.
I want some rectangles to be drawn on this JPanel.
I have a class named DrawRectPanel which extends JPanel and does all the drawing stuff.
The problem is that, I tried to draw the rectangles on panel1 by writing the following code :
panel1.add(new DrawRectPanel());
but nothing appeared on panel1
then I tried, just as a test to the class DrawRectPanel :
JFrame frame = new JFrame();
frame.setSize(1000, 500);
Container contentPane = frame.getContentPane();
contentPane.add(new DrawRectPanel());
frame.show();
This worked, and produced the drawings but on a separate JFrame
How can I draw the rectangles on panel1 ?
Thanks in advance.
EDIT :
code for DrawRectPanel
public class DrawRectPanel extends JPanel {
DrawRectPanel() {
Dimension g = new Dimension(400,400);
this.setPreferredSize(g);
System.out.println("label 1");
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("label 2");
g.setColor(Color.red);
g.fillRect(20, 10, 80, 30);
}
}
only label 1 is printed on the screen
still no idea,
for example
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class CustomComponent extends JFrame {
private static final long serialVersionUID = 1L;
public CustomComponent() {
setTitle("Custom Component Graphics2D");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void display() {
add(new CustomComponents());
pack();
// enforces the minimum size of both frame and component
setMinimumSize(getSize());
setVisible(true);
}
public static void main(String[] args) {
CustomComponent main = new CustomComponent();
main.display();
}
}
class CustomComponents extends JComponent {
private static final long serialVersionUID = 1L;
#Override
public Dimension getMinimumSize() {
return new Dimension(100, 100);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
#Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
}
instead of adding
contentPane.add(new DrawRectPanel());
you should do
contentPane.add(panel1);
Because you already have new DrawRectPanel in panel1. But in your code you are adding another instance of DrawRectPanel in contentPane. And never added panel1 in none of your container.
to fix your problem, change "paintComponent" to "paint" when the window repaints automatically, it should work.

Why does setting the layout to BorderLayout mean the paintComponent is never called

In the following example program, if you set useBorderlayout to true, the paintComponent method is never called - why?!
import javax.swing.*;
import java.awt.*;
public class PaintComponentTest extends JPanel {
private final boolean useBorderLayout;
public PaintComponentTest(boolean useBorderLayout){
this.useBorderLayout = useBorderLayout;
initialiseComponents();
}
public void initialiseComponents(){
setOpaque(true);
setBackground(Color.RED);
if(useBorderLayout){
//this appears to be the offending line:
setLayout(new BorderLayout());
}
final JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(Color.GREEN);
add(panel, BorderLayout.CENTER);
}
#Override
public void paintComponent(Graphics g){
System.out.println("PaintComponentTest.paintComponent");
super.paintComponent(g);
}
public static void main(String [] args){
final boolean useBorderLayout = (args.length == 1 && Boolean.parseBoolean(args[0]));
System.out.println("Running with"+(useBorderLayout?"":"out")+" BorderLayout as layout manager...");
SwingUtilities.invokeLater(new Runnable(){
public void run(){
final JFrame frame = new JFrame("BorderLayout/PaintComponent test");
frame.setPreferredSize(new Dimension(200, 200));
frame.getContentPane().setLayout(new BorderLayout());
final PaintComponentTest componentTest = new PaintComponentTest(useBorderLayout);
frame.getContentPane().add(componentTest);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
Because it doesn't need to. The PaintComponentTest class is a JPanel that has one green JPanel as content. When the BorderLayout is set, the green panel takes up all the space in panel and the PaintComponent method is not needed.
Add this method to your code and you should see it happen:
#Override
public void paintChildren(Graphics g){
System.out.println("PaintComponentTest.paintChildren");
super.paintChildren(g);
}
Because the nested panel covers all the component. Damaged region (to be repainted) is past to the children because the child bounds cover all the damaged region.

Categories

Resources