更换组件时,为什么必须在JFrame上使用setvisible()? [英] Why do I have to use setvisible() on my JFrame when I change components?
问题描述
因此,为了简单起见,我设置了一些测试代码来解决这个问题.基本上,我有一个JFrame
,并在其中添加了"this"(我从JComponent
扩展了主类以节省时间).此组件填充为红色背景.然后让它睡眠2秒钟,然后键入此内容.
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是我的JFrame
对象,而'thing'只是扩展JComponent
的另一个类,该类描绘了蓝色背景.
f being my JFrame
object and 'thing' is just another class extending JComponent
that paints a blue background..
当我注释掉setvisible()
时,它不再变为蓝色..我尝试使用t.setVisible(true),但看来我必须使框架再次可见,而不是组件
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?
推荐答案
"基本上,我有一个JFrame,我在其中添加了"this"(我刚刚从JComponent扩展了我的主类以节省时间).该组件填充为红色背景.然后我将其睡眠2秒钟,然后键入这个."
"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.Timer
to perform repeated tasks on the GUI or for animation. See more at How to Use Swing Timers. You can see a bunch ofTimer
examples here and here and here and here and here
使用CardLayout
可以尝试在视图之间进行切换,而不是尝试添加和删除面板.这将帮助您避免添加和删除components/containers
所带来的许多问题.有关更多信息,请参见如何使用CardLayout .另请参见此处的简单示例.
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.
要回答您的主要问题,每当从框架中删除和添加组件时,都需要revalidate()
. setVisible()
帮您解决这个问题.
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.
旁注
- 似乎很多情况下都添加了删除背景面板)只是为了更改背景.为什么不只是
setBackround()
?您可以使用Timer
切换颜色
- 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
这篇关于更换组件时,为什么必须在JFrame上使用setvisible()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!