3

I add a JButton to my JPanel subclass Quiz, and if I change either the text or the font of the button, the Quiz object disappears, showing only the panel underneath it. However, if I change the text or font before adding the button, everything works fine.

setupGraphics() gets called after the Quiz is added to the view hierarchy

public void setupGraphics() {
    this.setBackground(Color.red);
    setLayout(null);
    a.setBounds(20, 20, 200, 200);
    add(a);
    a.setText("Hi");
}

If I change the code to this:

public void setupGraphics() {
    this.setBackground(Color.red);
    setLayout(null);
    a.setBounds(20, 20, 200, 200);
    a.setText("Hi");
    add(a);
}

then it works.

Any ideas?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
frakjocker
  • 39
  • 1
  • 3
    Use an appropriate [LayoutManager](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) – copeg May 29 '15 at 18:19
  • 1
    Order should not matter, since Swing components are smart enough to paint themselves when a property is changed. So the problem is in the context of how you invoke this method. Post a proper [SSCCE](http://sscce.org/) that demonstrates the problem. – camickr May 29 '15 at 18:28
  • Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson May 30 '15 at 01:28

1 Answers1

-1

add(a); a.setText("Hi"); --> you are adding the button to the panel and then setting the text. That's y it is not displaying the text. For the second you are setting the text and other attributes and adding the button to the panel.

Shriram
  • 4,343
  • 8
  • 37
  • 64
  • `you are adding the button to the panel and then setting the text. That's y it is not displaying the text.` - it doesn't matter if you set the text after adding the button to the panel. Whenever you change a property of a Swing component the component will invoke revalidate() and repaint() on itself. – camickr May 29 '15 at 18:23
  • sorry i missed out mentioning the repaint(). – Shriram May 29 '15 at 18:25