所以我有这个问题。我在Java Eclipse SDK 4.2.1中编写了这段代码。我没有在这里写出所有的,actionPerformed方法现在是不相关的,它从Main调用一次。问题是有时当我运行它时,其中一个组件只是填满了整个窗口并与其他所有组件重叠。我尝试通过随机数字来改变大小,例如从400到350,有时它可以工作,然后再次打破。我可能错过了一些东西,我只是不知道是什么。我搜索了其他论坛,但没有发现任何关于它的信息。Java swing - 尺寸错误
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Window extends JFrame implements ActionListener
{
JTextField field1;
JTextField field2;
public Window()
{
super("Main Window");
setVisible(true);
setSize(500, 500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Initialize();
}
private void Initialize()
{
field1 = new JTextField();
field2 = new JTextField();
field1.setBounds(0, 0, 400, 100);
field2.setBounds(0,100,400,100);
add(field1);
add(field2);
field1.setBackground(Color.PINK);
field1.setForeground(Color.RED);
field2.setBackground(Color.PINK);
field2.setForeground(Color.RED);
JButton button = new JButton("Create");
button.setBounds(0, 200, 400, 100);
add(button);
button.setBackground(Color.BLACK);
button.setForeground(Color.YELLOW);
button.addActionListener(this);
}
*“然后再次破坏”*从代码在帧上设置显式大小并限制测试字段的那一刻起,IT就被打破了。另外,确保GUI构建在EDT上。为了更快地获得更好的帮助,请发布[SSCCE](http://sscce.org/)。 – 2013-03-09 16:59:58
顺便说一句 - *“SDK 4.2.1”*我第一次读取该数字为'1.4.2'。什么是Java版本'4.2.1'? – 2013-03-09 17:07:52
BTW2 - 该GUI似乎试图将3个组件放在一个大小相同的垂直列中。使用'GridLayout' - 这是完美的使用。 – 2013-03-09 17:20:16