在Java中关闭帧

在Java中关闭帧,java,Java,我想知道是否有人能向我解释为什么我的这个不能编译?当用户点击[x]按钮时,我试图关闭java中的一个帧。我不确定您是否需要java中的侦听器或类似的东西,但自从我查找这个问题以来,似乎这就是您所需要的 import javax.swing.JFrame; public class BallWorld { public static void main( String[] args ) { BallWorldFrame world = new BallWorldFrame();

我想知道是否有人能向我解释为什么我的这个不能编译?当用户点击[x]按钮时,我试图关闭java中的一个帧。我不确定您是否需要java中的侦听器或类似的东西,但自从我查找这个问题以来,似乎这就是您所需要的

import javax.swing.JFrame;

public class BallWorld
{
  public static void main( String[] args )
  {
    BallWorldFrame world = new BallWorldFrame();
    world.setDefaultCloseOperation(world.DISPOSE_ON_CLOSE);
    world.setVisible( true );

   }


  }

这不起作用的原因是您的
BallWorldFrame
类没有您试图调用的方法。试试这个:

public class BallWorldFrame extends JFrame {
    ...
}
请注意,我们正在进行扩展,从而允许我们使用
setDefaultCloseOperation
setVisible
等方法


现在,要创建一个关闭框架的按钮,需要使用
ActionListener
。您可以尝试以下方法(将所有内容放在一个类中):


注意我们的类现在是如何实现
ActionListener
并重写
actionPerformed
来关闭框架的。通过
x.addActionListener(this)
,我们的意思是“单击“x”按钮时,执行类的
actionPerformed
方法中定义的操作,即关闭框架”。

根据您所说,听起来您的
BallWorldFrame
并不是从
JFrame
扩展而来,因为默认的关闭操作是
JFrame

尝试一个更简单的例子:

public static void main(String[] args) {

    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {

            BallWorldFrame world = new BallWorldFrame();
            // All these compile and run without issue...
            world.setDefaultCloseOperation(world.DISPOSE_ON_CLOSE);
            world.setDefaultCloseOperation(BallWorldFrame.DISPOSE_ON_CLOSE);
            world.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            world.setVisible(true);

        }
    });

}

public static class BallWorldFrame extends JFrame {
}

注意,
static
declaration来自这样一个事实,即在我的示例中,
BallWorldFrame
是我的主类的一个内部类。如果您的
BallWorldFrame
存在于它自己的类文件中,它将不需要它。

它不喜欢“world.setDefaultCloseOperation(world.DISPOSE\u ON\u CLOSE);编译错误消息是什么?”这一行“不是足够的问题描述。如果您将
world.DISPOSE\u ON\u CLOSE
更改为
BallWorldFrame.DISPOSE\u ON\u CLOSE
,该怎么办?很抱歉,我尝试了您的建议,但遗憾的是,它什么也没做。我在Eclipse中运行,它说DISPOSE_ON_CLOSE不能解析为类型或不是字段。它不会让我运行它。嘿,刘易斯,我已经尝试过扩展JFrame,但仍然没有发生任何事情。你能给我们提供
BallWorldFrame
的定义吗?作为
world.DISPOSE\u ON\u CLOSE
不应停止程序运行,尽管首选方法是
JFrame。DISPOSE\u ON\u CLOSE
BallWorld
BallWorldFrame
不同。如果不知道BallWorldFrame实际上是什么,就很难确切知道问题所在:p谢谢你的帮助!但尽管如此,即使在我扩展JFrame时,它也会显示关于setDefaultCloseOperation的相同错误消息。有什么想法吗?@EricSage抱歉,我的意思是有
BallWorldFrame
extend
JFrame
。@OP当然,你一般应该避免使用类似
world.DISPOSE\u ON\u CLOSE
(因为
DISPOSE\u ON\u CLOSE
静态的)。
public static void main(String[] args) {

    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {

            BallWorldFrame world = new BallWorldFrame();
            // All these compile and run without issue...
            world.setDefaultCloseOperation(world.DISPOSE_ON_CLOSE);
            world.setDefaultCloseOperation(BallWorldFrame.DISPOSE_ON_CLOSE);
            world.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            world.setVisible(true);

        }
    });

}

public static class BallWorldFrame extends JFrame {
}