默认关闭JFrame的操作不起作用

时间:2013-10-29 22:33:42

标签: java swing jframe dispose

我正在使用NetBeans。 我的JFrame具有默认关闭操作:EXIT_ON_CLOSE。 我有一个按钮,该按钮应关闭此JFrame上的程序,这是执行动作的代码:

private void bSalirActionPerformed(java.awt.event.ActionEvent evt){                                       
    this.dispose();
}  

我认为这会关闭所有程序的JFrame,但它没有,你能解释一下为什么或如何修复它?

5 个答案:

答案 0 :(得分:2)

假设您调用了JFrame 框架,如下所示:

JFrame frame = new JFrame();

您可以通过调用

关闭它
frame.dispose();

另外,调用this.dispose()是指您在类中定义的dispose()方法。这可能是它无法正常工作的原因。你的课程中有一种名为dispose的方法吗?如果是这样,这种方法到底是做什么的?

答案 1 :(得分:2)

构建框架时调用frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)。在actionPerformed方法中,请致电frame.dispose()&只要没有其他非守护程序线程在运行,JVM就应该结束。

在简短的演示中可以看到

DISPOSE_ON_CLOSE。在this answer

  

..我认为这会关闭所有jFrame ..

应该只有一个(尽管上面的屏幕截图,因为它是一个人为的情况)。请参阅The Use of Multiple JFrames, Good/Bad Practice?以上演示将在第3帧关闭后关闭。

答案 2 :(得分:2)

  

EXIT_ON_CLOSE

当您单击框架右上角的“X”按钮时会发生这种情况。

您的ActionListener正在当前帧上调用dispose()。如果这是唯一的打开框架,那么应用程序也将关闭,但dispose方法不会关闭所有打开的框架/对话框。

结帐Closing an Application。如果要关闭整个应用程序,可以使用ExitAction作为按钮,因为它会模拟用户点击“X”按钮。

答案 3 :(得分:1)

如果您想使用按钮退出应用程序,则可以使用System.exit()frame.dispose()

但请注意System.exit(),因为这会终止JVM

所以最好先在用户之前确认。 与JOptionPane.showConfirmDialog();

private void bSalirActionPerformed(java.awt.event.ActionEvent evt){ 

        int exit = JOptionPane.showConfirmDialog(
                frame,
                "Are you sure you want to exit the application?",
                "Exit Application",
                JOptionPane.YES_NO_OPTION);                             
        if(JOptionPane.YES_OPTION == exit){
             frame.dispose(); // or System.exit(1);
        }
    }

答案 4 :(得分:0)

我使用下面的方法,只需调用此mesthod,它将关闭当前窗口/ jFrame:

  private void close(){
    WindowEvent windowEventClosing = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
    Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowEventClosing);     
}

同时设置' defaultCloseOperation'根据您的需要,属性中的 jFrame