如前所述,我是一个新手,并希望创建一个按钮来关闭程序。我不是在谈论确保典型的窗口关闭(红色 X)会终止程序。我希望在我的框架中创建一个额外的按钮,单击该按钮也会终止程序。
问问题
323 次
4 回答
5
您可以将ActionListener添加到您的按钮,该按钮在执行操作后会从 JVM 退出。
yourButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
于 2012-08-27T00:27:04.640 回答
5
如果您已将主应用程序框架的 ( JFrame
)defaultCloseOperation
设置为,JFrame.EXIT_ON_CLOSE
那么只需调用框架的dispose
方法即可终止程序。
JButton closeButton = JButton("Close");
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
yourReferenceToTheMainFrame.dispose();
}
});
如果没有,那么您将需要向该actionPerformed
方法添加一个调用System.exit(0);
于 2012-08-27T00:27:18.727 回答
2
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);
}
}
于 2012-08-27T03:23:19.050 回答
1
如果您正在扩展 org.jdesktop.application.Application 类(Netbeans 会这样做),您可以在您的应用程序类中调用 exit(),因此:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
yourApp.exit();
}
});
于 2012-08-27T00:35:41.547 回答