0

我决定在我的 JFrame 上放置“关闭”按钮。如果我只测试那个 JFrame 本身,它工作正常,但是当我通过另一个类打开它后尝试关闭它时,它不会关闭。

这是代码:

JButton btnClose = new JButton("Close");
btnClose.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        frame.dispose();
    }
});
btnClose.setBounds(282, 666, 96, 50);
contentPane.add(btnClose);

我尝试过使用frame.dispose()and frame.close()super.dispose()但唯一有效的方法是system.exit(0);退出整个程序。

问题:

  • 如果我自己测试JFrame,框架会很好地关闭。
  • 如果我打开程序并导航到那个特定JFrame的,关闭按钮什么也不做。

请指教。

4

2 回答 2

1

您是否在 ActionListener 中添加了一条显示语句以确保正在执行代码?

如果正在执行代码,那么问题可能是帧变量的引用无效。

您不需要保留对框架的引用。而是使用类似的东西:

Window window = SwingUtilities.windowForComponent( e.getSource() );
window.dispose();
于 2013-10-02T19:09:33.913 回答
0

Use setVisible(false); on the frame. Then call dispose.

于 2013-10-02T17:34:35.063 回答