单击按钮后关闭 JFrame Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17011991/
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
Closing a JFrame after a button is clicked Java
提问by The Progenitor
Hello I am writing a sort of Menu for an encryption program I am writing. I finished the core of it, and now i want to try to create a GUI for it. Here is the code for the first Menu:
您好,我正在为我正在编写的加密程序编写一种菜单。我完成了它的核心,现在我想尝试为它创建一个 GUI。这是第一个菜单的代码:
package matrix_with_GUI;
import javax.swing.*;
import java.awt.event.* ;
import java.awt.* ;
public class Main_Menu extends JFrame implements ActionListener{
private JButton action1 = new JButton ("");
private JButton action2 = new JButton ("");
private JPanel pane = new JPanel();
private JLabel lbl;
public static void main(String[] args) {
Main_Menu main = new Main_Menu();
}
public Main_Menu(){
super();
JPanel pane=new JPanel();
setTitle ("Start Menu") ;
JFrame frame = new JFrame("");
setVisible(true);
setSize (380, 260) ;
setLocation (450, 200) ;
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;
action1 = new JButton("Start");
action2 = new JButton("Exit");
lbl = new JLabel ("Welcome to the Matrix Encoder/Decoder!!!");
setLayout(new FlowLayout());
add (lbl) ;
add(action1, BorderLayout.CENTER);
action1.addActionListener (this);
add(action2, BorderLayout.CENTER);
action2.addActionListener (this);
}
@Override
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
OptionsMenu x = new OptionsMenu();
if (event.getSource() == action1)
{
System.exit(0);
x.OptionsMenu();
}
else if(event.getSource() == action2){
System.exit(0);
}
}
} When the Start Button is clicked, the new menu comes up all fine and good, but the first menu stays open. Is there a way to close this first menu AND open the second menu with the first button click? I'm very new to GUI so the simplest solution would be very helpful. On a side note is there a simple way to move the Start button to the next line? Thanks
当点击开始按钮时,新菜单出现的很好,但第一个菜单保持打开状态。有没有办法关闭第一个菜单并通过单击第一个按钮打开第二个菜单?我对 GUI 很陌生,所以最简单的解决方案会非常有帮助。附带说明一下,是否有一种简单的方法可以将“开始”按钮移动到下一行?谢谢
回答by user2277872
You have 2 options: you can use a Window Listener, or you can use the dispose() method. To do the dispose() just type
您有 2 个选择:您可以使用 Window Listener,或者您可以使用 dispose() 方法。要执行 dispose() 只需键入
* This is better to be used with subframes and 2nd level windows.*
this.dispose();
or check this link for using the window listener
或检查此链接以使用窗口侦听器