使用 JButton 关闭 JFrame

Closing JFrame with a JButton

这段代码有问题,无法编译。你可以帮帮我吗 ? 我需要在单击按钮时关闭 JFrame

public class SlotMachine extends JFrame
{
    /*
     *
     */
    JButton btnExit = new JButton("Exit");
    btnExit.addMouseListener(new MouseAdapter() 
    {
        @Override
        public void mouseClicked(MouseEvent arg0) 
        {
            this.dispose();
        }
    });
}

错误是 = 新的 MouseAdapter() 类型未定义方法 dispose(){}

我不知道如何从 mouseClicked 方法获取 SlotMachine 对象

您正在调用 this.dispose(); 这里的关键是 this 指的是内部 class、MouseListener,而 MouseListener 没有 dispose() 方法.

解决方案:删除 this,它应该可以工作,因为如果内部 class 不包含该方法,编译器将查看外部 class。或者你可以指定 which 你的意思是:SlotMachine.this.dispose(); 将告诉编译器调用外部 SlotMachine class.

的方法

出于以下几个原因在 JButton 上使用 ActionListener:

  • 如果按钮有焦点,按钮的默认行为是按空格键激活。这不适用于 MouseListener。
  • 还有一个预期的行为是,如果通过 setEnabled(false) 禁用了按钮,则按下它不应导致触发操作。这不适用于 MouseListener 但适用于 ActionListener。
  • 您可以轻松地与包括 JMenuItems 在内的其他组件共享 ActionListener(或者更好的是,一个 AbstractAction)。