无法使用setDefaultCloseOperation关闭窗口

0 java swing compiler-errors jframe

我是Java的新手,我在这个简单的代码中找不到我的错误.错误是关闭操作不起作用:

error: cannot find symbol
Run Code Online (Sandbox Code Playgroud)

以上是编译错误.这是代码.

import javax.swing.*;
import java.awt.*;
class UseButton extends Frame {

    public static void main(String...args) {
        UseButton btn = new UseButton();
        btn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        btn.setSize(200, 150);
        btn.setVisible(true);

    }
    private JButton b;
    private JTextField text;

    public UseButton() {
        super("title");
        setLayout(new FlowLayout());

        b = new JButton("OK");
        add(b);
    }
}
Run Code Online (Sandbox Code Playgroud)

Mad*_*mer 7

java.awt.Frame没有调用的方法setDefaultCloseOperation,我想你想用javax.swing.JFrame

话虽如此,你不应该从顶级容器扩展目录JFrame,这是不好的做法,因为你没有真正为类增加任何价值,降低了你的类的可重用性(因为你不能添加它可以解决任何问题)并将您锁定在一个演示实现中......您可以将其添加到其他任何内容中......

坏...

class UseButton extends Frame{
Run Code Online (Sandbox Code Playgroud)

好...

class UseButton extends JFrame{
Run Code Online (Sandbox Code Playgroud)

更好...

import java.awt.EventQueue;
import java.awt.Frame;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class UseButton {

    public static void main(String... args) {
        new UseButton();

    }

    public UseButton() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JButton b;
        private JTextField text;

        public TestPane() {
            b = new JButton("OK");
            add(b);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)