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

只谈情不闲聊 提交于 2019-12-11 19:51:10

问题


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."

  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



回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!