Java如何禁用JFrame关闭按钮?
要禁用对a的关闭操作JFrame,当用户单击上的关闭图标时JFrame,我们可以将默认关闭操作的值设置为WindowConstants.DO_NOTHING_ON_CLOSE。
package org.nhooo.example.swing; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.HeadlessException; public class DisableCloseButtonDemo extends JFrame { public DisableCloseButtonDemo() throws HeadlessException { initialize(); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> new DisableCloseButtonDemo().setVisible(true)); } private void initialize() { //WindowConstants.DO_NOTHING_ON_CLOSE告诉JFrame实例要做 //发生窗口关闭事件时没有任何反应。 this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); JButton button = new JButton("Close"); button.addActionListener(e -> System.exit(0)); this.setLayout(new FlowLayout(FlowLayout.CENTER)); this.setSize(new Dimension(100, 100)); this.getContentPane().add(button); } }