如何点击 Java 中按钮关闭 JFrame
设置 frame.dispose() 以在单击按钮后关闭 JFrame。首先创建按钮和框架 -
JFrame frame = new JFrame();
JButton button = new JButton("Click to Close!");现在,使用 Action Listener 在单击上述按钮后关闭 JFrame -
button.addActionListener(e -> {
frame.dispose();
});以下示例演示了在单击按钮后关闭 JFrame -
示例
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame();
JButton button = new JButton("Click to Close!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(button);
button.addActionListener(e -> {
frame.dispose();
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(550, 300));
frame.getContentPane().setBackground(Color.ORANGE);
frame.pack();
frame.setVisible(true);
}
}输出

单击按钮“Click to Close”时,框架将关闭。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP