java 当 setVisible(false) 时 JFrame 不隐藏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1450475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JFrame does not hide when setVisible(false)
提问by user176136
import javax.swing.*;
class Frame extends JFrame{
Frame() {
JFrame j = new JFrame();
j.setBounds(100, 200, 120, 120);
j.setTitle("null");
j.setVisible(true);
j.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
public class test001 {
public static void main (String Args[]){
Frame f = new Frame();
System.out.print("Visible = True");
f.setVisible(false);
System.out.print("Visible = false");
}
}
after the setVisible(false) command. The JFrame Window still show on my desktop. How can I fix that ?
在 setVisible(false) 命令之后。JFrame 窗口仍然显示在我的桌面上。我该如何解决?
回答by JRL
You're creating another JFramewithin your constructor. Assuming what you want is your Frameclass to be invisible, do this:
您正在JFrame构造函数中创建另一个。假设您想要的是您的Frame班级不可见,请执行以下操作:
class Frame extends JFrame {
Frame() {
setBounds(100, 200, 120, 120);
setTitle("null");
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
public class test001 {
public static void main(String Args[]) {
Frame f = new Frame();
System.out.print("Visible = True");
f.setVisible(false);
System.out.print("Visible = false");
}
}
回答by Peter ?tibrany
Problem is that your main method uses different JFrame that your constructor. Your Frame constructor creates new JFrame instance (using new JFrame). When you call f.setVisible(false), it goes to your frame, but not to created JFrame.
问题是您的主要方法使用与您的构造函数不同的 JFrame。您的 Frame 构造函数创建新的 JFrame 实例(使用新的 JFrame)。当您调用 f.setVisible(false) 时,它会转到您的框架,但不会转到创建的 JFrame。
回答by Timothy Pratley
The problem here is that your "Frame" class instanciates a new JFrame. Calling setVisible on the Frame does not affect the JFrame which is being shown.
这里的问题是您的“Frame”类实例化了一个新的 JFrame。在 Frame 上调用 setVisible 不会影响正在显示的 JFrame。
You can fix it by either just using a JFrame instance, or just subclassing. Don't do both.
您可以通过仅使用 JFrame 实例或仅通过子类化来修复它。不要两者都做。
回答by digital_infinity
Besides the two different frames you are referring to (this is the problem answered https://stackoverflow.com/a/1450488/1326149), you should do all the graphics operations in the EVT thread (because your program even if it works great for you could be not portable to different platforms).
除了您所指的两个不同的帧(这是https://stackoverflow.com/a/1450488/1326149回答的问题),您应该在 EVT 线程中执行所有图形操作(因为您的程序即使它运行良好因为您可能无法移植到不同的平台)。

