问题
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?
回答1:
"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."
Don't "sleep" your program. Instead use a
java.swing.Timerto perform repeated tasks on the GUI or for animation. See more at How to Use Swing Timers. You can see a bunch ofTimerexamples here and here and here and here and hereInstead of trying to add and remove panels look into using a
CardLayoutwhich allows you to switch between views. It will help you avoid a lot of problems that come with with adding and removingcomponents/containers. See more at How to Use CardLayout. Also see a simple example here.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 theTimer
回答2:
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.
来源:https://stackoverflow.com/questions/22609593/why-do-i-have-to-use-setvisible-on-my-jframe-when-i-change-components