更换组件时,为什么必须在JFrame上使用setvisible()? [英] Why do I have to use setvisible() on my JFrame when I change components?

查看:64
本文介绍了更换组件时,为什么必须在JFrame上使用setvisible()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,为了简单起见,我设置了一些测试代码来解决这个问题.基本上,我有一个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."

  1. 不要睡眠" 您的程序.而是使用java.swing.Timer在GUI上执行重复的任务或动画.有关更多信息,请参见如何使用摇摆计时器.您可以在此处此处此处

  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

使用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 the Timer

这篇关于更换组件时,为什么必须在JFrame上使用setvisible()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆