我在 Eclipse 中创建一个简单的 Java JFrame,带有一个标签、2 个带有 2 个文本字段的单选按钮和一个 JButton。当我运行程序时,其中的对象被弄乱了,按钮和文本字段不显示,有时文本字段会占用整个框架的大小。但是,当我最小化/最大化框架然后恢复它时,它们可以正常工作。这是代码:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class myframe {
public static void main(String s[]) {
JFrame frame = new JFrame("Title");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// This is an empty content area in the frame
JLabel jlbempty = new JLabel("");
jlbempty.setPreferredSize(new Dimension(500, 400));
frame.getContentPane().add(jlbempty, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.setBounds(0, 0, 500, 400);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(Box.createRigidArea(new Dimension(0,5)));
panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
JLabel label = new JLabel("My label");
panel.add(label);
JPanel buttonPane = new JPanel();
frame.add(buttonPane);
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JRadioButton cb = new JRadioButton("1");
buttonPane.add(cb);
JTextField tf = new JTextField(0);
tf.setText("");
buttonPane.add(tf);
JPanel panel3 = new JPanel();
frame.add(panel3);
panel3.setLayout(new BoxLayout(panel3, BoxLayout.LINE_AXIS));
panel3.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JRadioButton cb2 = new JRadioButton("2");
panel3.add(cb2);
JTextField tf2 = new JTextField(0);
tf.setText("");
panel3.add(tf2);
JPanel panel2 = new JPanel();
JButton button = new JButton("click me");
frame.add(panel2);
panel2.add(button);
button.addActionListener(new Action());
panel.add(buttonPane);
panel.add(panel3);
panel.add(panel2);
}
static class Action implements ActionListener{
public void actionPerformed(ActionEvent arg0) {
JFrame frame2 = new JFrame("Clicked");
frame2.setVisible(true);
frame2.setSize(100, 200);
JLabel label2 = new JLabel("You clicked me");
JPanel panel2 = new JPanel();
frame2.add(panel2);
frame2.add(label2);
}
}
}