所以我有這個問題。我在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