我有一个问题。我在Java Eclipse SDK 4.2.1中编写了这段代码,由于篇幅原因我没有全部展示,现在actionPerformed方法不相关,从Main中调用。问题是有时候当我运行它时,其中一个组件会填充整个窗口并覆盖其他所有组件。我尝试通过随机数字更改大小,例如从400到350,有时它可以正常工作,然后又会出现问题。我可能遗漏了某些东西,但我不知道是什么。我搜索了其他论坛,但没有找到任何相关信息。
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);
}
GridLayout
- 它非常适合这种用途。 - Andrew Thompson