我是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.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);
}
}
答案 0 :(得分:7)
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);
}
}
}
答案 1 :(得分:0)
错误是关闭操作无效:
error: cannot find symbol
仅在JFrame(Swing库)中使用setDefaultCloseOperation。是的,我同意@MadProgrammer。
所以我分析,您想在AWT库中使用Frame。像下面的代码一样:
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);
}
});
}
}