简体   繁体   中英

Why do I have to use setvisible() on my JFrame when I change components?

So for the sake of simplicity I set up a little test code just to figure out this problem. Basically I have a JFrame and I added 'this' to it (I just extended my main class from JComponent to save time). this component fills in a red background. Then I have it sleep for 2 seconds and then type this.

f.remove(this);
thing t = new thing();
f.add(t);
f.setVisible(true);

f being my JFrame object and 'thing' is just another class extending JComponent that paints a blue background..

when I comment out setvisible() it no longer changes to blue.. I've tried using t.setVisible(true) but it seems I have to make the frame visible again, not the component

does anyone know why I have to call that... or if there is another way to change components within a single frame?

"Basically I have a JFrame and I added 'this' to it (I just extended my main class from JComponent to save time). this component fills in a red background. Then I have it sleep for 2 seconds and then type this."

  1. Don't "sleep" your program. Instead use a java.swing.Timer to perform repeated tasks on the GUI or for animation. See more at How to Use Swing Timers . You can see a bunch of Timer examples here and here and here and here and here

  2. Instead of trying to add and remove panels look into using a CardLayout which allows you to switch between views. It will help you avoid a lot of problems that come with with adding and removing components/containers . See more at How to Use CardLayout . Also see a simple example here .

  3. To answer your main question, whenever you remove and add components from your frame, you need to revalidate() it. setVisible() takes care of that for you.


Side Note

  • Seems like a lot adding an removing background panels) just to change the background. Why not just setBackround() ? You can switch colors with the use of the Timer

Calling setVisible(true) makes the frame appear onscreen. Sometimes you might see the show method used instead. The two usages are equivalent, but we use setVisible(true) for consistency's sake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM