我目前正在使用 Eclipse 的拖放功能,我有一个默认带有 JFrame 的应用程序窗口,并且能够 setVisible(false);
但我有其他框架/面板/窗口使用 JPanel 创建并扩展 JFrame。
因为 extend
我无法 setVisible(false or true);
它对窗口没有任何影响,它仍然保持为真。
我的代码:
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LibrarianMenu frame = new LibrarianMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public LibrarianMenu() {
setTitle("Librarian");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 385, 230);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
.
.
. so on
我在这里尝试执行我的按钮:
btnLogout.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
LibrarianMenu frame = new LibrarianMenu();
frame.setVisible(false);
}
});
有什么解决办法吗?
最佳答案
因为您是在 Runnable 内部创建框架,所以它的范围仅限于 runnable。尝试在 runnable 之外声明变量,然后在 runnable 内初始化它,如下所示:
private JPanel contentPane;
private LibrarianMenu frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new LibrarianMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
然后在不声明 LibrarianMenu 的新实例的情况下将可见设置为 false:
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
});
关于java - 使用按钮关闭 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36739800/