2013-10-05 69 views
0

我想要做的是有一个JButton,当您点击它时,它将关闭JFrame /应用程序。我有一个JButton,但我想知道如何使它关闭当前打开的窗口。使用JButton关闭当前打开的应用程序

+1

1)使用['setDefaultCloseOperation(DISPOSE_ON_CLOSE)'](http://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation%28int%29 )。 “按钮”(框架右上方)内置。 2)*“谢谢,诺亚”*噪音,不要说了。 –

回答

1

只需使用JFrame的dispose()方法即可。见Javadoc

附录:另外,您可能希望将JFrame的默认关闭操作设置为“退出”,而不是默认的“隐藏”。当你创建你的框架时做。

JFrame frame = new JFrame(); 
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 

// Do whatever your application does. 

frame.dispose(); // With this you close the frame. 
+1

*“..”退出“,而不是默认的”隐藏“。”*更好的是'DISPOSE_ON_CLOSE'。它将只在所有非守护线程完成运行后退出虚拟机。如果虚拟机在帧关闭后一直运行无限,这是程序员需要明确清理/关闭的线程的迹象。 –

2

JButtonactionPerformed(),只需添加System.exit(0)。你已准备好出发。

+0

@AndrewThompson哦,是的。非零意味着异常终止。 –

+0

@AndrewThompson有点难以摆脱MR。但是..我认为你应该在那里留下'噪音'。 –

+0

呃(耸耸肩)如果这个人编辑的答案包括建议(这是我的偏好),评论就变成了噪音。 –

3

将一个监听器注册到您的按钮,然后在单击按钮上调用System.exit(0)。

JButton button = new JButton("Close"); 
button.addActionLister(new ActionListener(){ 

    public void actionPerformed(ActionEvent e){ 
     System.exit(0); 
    } 
}); 
+1

*“可能会因为我在没有IDE的情况下编写此代码而发生语法更改”*不错,给出您从..memory,experience ..类型输入的内容。在使用我的编译器检查细节之后,我做了一些调整。 –

+0

谢谢@AndrewThompson :) – dinukadev

0

只需调用JFrame的Dispose()方法,随后System.exit(0)

+0

此消息是为Dinukadev – Noah

+0

此消息是为了Dinukadev – Noah

+0

我不这么认为,这是操作系统的一部分。也许你可以创建自己的外观和感觉,并为你的应用程序明确设置它。 – MeBNoah

1

见从Closing an ApplicationExitAction

这种方法与其他建议有点不同,因为它会将windowClosing()事件分派给Window。这将导致窗口基于窗口的关闭选项关闭,并将调用您可能已添加到窗口以处理windowClosing()事件的任何窗口侦听器。

0

使从包含的JFrame应用程序中的类的对象,然后dispose它在一个按钮事件监听器:

为前。

public class Application extends JFrame { 
     private static final long serialVersionUID = 1L; 
     static Application app= new Application(); 

    public Application{ 
     setLayout(new FlowLayout()); 
     Container pane =this.getContentPane(); 

     JPanel right = new JPanel(); 
     right.setLayout(new GridLayout(4,1)); 



     ButtonEvent = new JButton("Button"); 
     right.add(whiteList); 


     pane.add(right); 

} 

    public class ButtonEvent implements ActionListener{ 
    public void actionPerformed (ActionEvent event){ 
     app.dispose(); 
     dispose(); 
    } 

} 


public static void main(String args[]){ 
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    app.setVisible(true); 
    app.setTitle("Application"); 
    app.setSize(700,500); 
    app.setLocation(350, 100); 
    } 
} 
相关问题