Java swing 的Jframe中如何通过按钮来实现停止程序的运行
时间: 2024-04-16 13:26:49 浏览: 16
您可以通过在按钮的 ActionListener 中调用 System.exit(0) 来停止程序的运行。下面是一个简单的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class StopProgram extends JFrame {
public StopProgram() {
JButton stopButton = new JButton("停止程序");
stopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setLayout(new FlowLayout());
add(stopButton);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new StopProgram();
}
});
}
}
```
在上述示例中,我们创建了一个 JFrame,其中包含一个名为 "停止程序" 的按钮。当用户点击按钮时,ActionListener 中的 actionPerformed 方法会被调用,然后通过调用 System.exit(0),程序会立即退出。