需要关于为小型Java程序创建关闭按钮的建议吗
如前所述,我是一个新手,希望创建一个按钮来关闭程序。我不是说确保典型的窗口关闭(红色X)终止程序。我希望在我的框架内创建一个额外的按钮,单击该按钮也将终止程序。您可以向按钮添加一个按钮,该按钮在执行操作时从JVM退出需要关于为小型Java程序创建关闭按钮的建议吗,java,swing,Java,Swing,如前所述,我是一个新手,希望创建一个按钮来关闭程序。我不是说确保典型的窗口关闭(红色X)终止程序。我希望在我的框架内创建一个额外的按钮,单击该按钮也将终止程序。您可以向按钮添加一个按钮,该按钮在执行操作时从JVM退出 yourButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0);
yourButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
如果已将主应用程序框架的(
JFrame
)defaultCloseOperation
设置为JFrame。在关闭时退出
,然后只需调用框架的dispose
方法即可终止程序
JButton closeButton = JButton("Close");
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
yourReferenceToTheMainFrame.dispose();
}
});
如果没有,则需要向
actionPerformed
方法添加对System.exit(0)的调用代码>如果要扩展org.jdesktop.application.application类(Netbeans会这样做),可以在应用程序类中调用exit(),因此:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
yourApp.exit();
}
});
我更喜欢DISPOSE\u ON\u CLOSE
(参见我的答案)。但是+1。@AndrewThompson这是一个公平的观点,值得记住,干杯
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class GoodbyeWorld {
GoodbyeWorld() {
final JFrame f = new JFrame("Close Me!");
// If there are no non-daemon threads running,
// disposing of this frame will end the JRE.
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// If there ARE non-daemon threads running,
// they should be shut down gracefully. :)
JButton b = new JButton("Close!");
JPanel p = new JPanel(new GridLayout());
p.setBorder(new EmptyBorder(10,40,10,40));
p.add(b);
f.setContentPane(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
ActionListener closeListener = new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
f.setVisible(false);
f.dispose();
}
};
b.addActionListener(closeListener);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
new GoodbyeWorld();
}
};
SwingUtilities.invokeLater(r);
}
}