Java 无法使用setDefaultCloseOperation关闭窗口
我是Java新手,在这个简单的代码中找不到我的错误。错误是关闭操作不起作用:Java 无法使用setDefaultCloseOperation关闭窗口,java,swing,compiler-errors,jframe,Java,Swing,Compiler Errors,Jframe,我是Java新手,在这个简单的代码中找不到我的错误。错误是关闭操作不起作用: error: cannot find symbol 上面是编译错误。这是代码 import javax.swing.*; import java.awt.*; class UseButton extends Frame { public static void main(String...args) { UseButton btn = new UseButton(); btn
error: cannot find symbol
上面是编译错误。这是代码
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);
}
}
java.awt.Frame没有名为setDefaultCloseOperation的方法,我想您应该使用javax.swing.JFrame
话虽如此,您不应该从顶级容器(如JFrame)扩展目录,这是一种糟糕的做法,因为您没有真正为类添加任何值,降低了类的可重用性,因为您无法将其添加到任何其他内容中,并将其锁定到单个表示实现中……您可以将其添加到任何其他内容中
坏
class UseButton extends Frame{
好的
class UseButton extends JFrame{
更好
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);
}
}
}
错误是关闭操作不起作用:
error: cannot find symbol
错误:找不到符号
原因:仅在JFrame Swing库中使用setDefaultCloseOperation。是的,我同意@MadProgrammer
所以我的分析,你们想在AWT库中使用框架。如下代码所示:
import java.awt.event.*;
import java.awt.*;
class UseButton extends Frame {
public static void main(String...args) {
UseButton btn = new UseButton();
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);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
}
}
你好你能加上你在问题上的错误吗?您可以添加的信息越多,我们可以提供的帮助就越多。这里是it错误:找不到symbolthanks的家伙!它已经成功了。我如何使用它,我应该扩展它而不是Frame@mamur将类UseButton扩展帧更改为类UseButton扩展JFrame@mamur抱歉,误解了您的评论,请检查updateThanks以了解此建议。如果它有助于解决问题,请检查updateThanks。