我目前正在学习java,而且我已经暂时停留在这个问题上了一段时间。 我重新安装了java(最新版本,1.8.0_25),但问题仍然存在。
每当我尝试从JComponent类中添加任何可视化内容时,都会出现这个奇怪的错误,而我无法弄清楚导致它的原因。
import javax.swing.*;
import java.awt.*;
class Start {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello!");
JButton button = new JButton("Click me!");
JLabel label = new JLabel("woah");
JTextField textField = new JTextField(12);
frame.setDefaultCloseOperation(3);
frame.setVisible(true);
frame.setSize(250, 250);
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
p1.setLayout(new FlowLayout());
p1.add(textField);
p1.add(label);
p2.add(button);
frame.add(p1, BorderLayout.NORTH);
frame.add(p2, BorderLayout.SOUTH);
}
}
答案 0 :(得分:0)
frame.setDefaultCloseOperation(3)
),它们对大多数人没什么意义,价值可以改变,改为使用常数,例如frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
例如
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
class Start {
public static void main(String[] args) {
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("Hello!");
JButton button = new JButton("Click me!");
JLabel label = new JLabel("woah");
JTextField textField = new JTextField(12);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
p1.setLayout(new FlowLayout());
p1.add(textField);
p1.add(label);
p2.add(button);
frame.add(p1, BorderLayout.NORTH);
frame.add(p2, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
在某些机器上也存在Java 8的问题,但这应该纠正大多数"他们......