有一段简单的界面布局代码如下:
username = new JTextField(20);
password = new JPasswordField(20);
submitButton = new JButton("确定");
cancelButton = new JButton("取消");
GridBagLayout gridBagLayout = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
mainPanel.setLayout(gridBagLayout);
gbc.anchor=GridBagConstraints.SOUTHWEST;
Insets insets = new Insets(5, 50, 5, 5);
gbc.insets = insets;
gbc.gridx=1;
gbc.gridy=1;
mainPanel.add(new JLabel(" "),gbc);
gbc.gridx=2;
gbc.gridy=2;
mainPanel.add(new JLabel(" "),gbc);
gbc.gridx=3;
gbc.gridy=3;
mainPanel.add(new JLabel(" "),gbc);
gbc.gridx=3;
gbc.gridy=4;
mainPanel.add(new JLabel(" "),gbc);
//username
gbc.gridx=3;
gbc.gridy=5;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.NONE;
mainPanel.add(username, gbc);
//password
gbc.gridy=GridBagConstraints.RELATIVE;
gbc.gridwidth = GridBagConstraints.REMAINDER;
mainPanel.add(password, gbc);
//submit
gbc.gridy=GridBagConstraints.RELATIVE;
gbc.gridwidth = 1;
mainPanel.add(submitButton, gbc);
//cancel
gbc.gridx=GridBagConstraints.RELATIVE;
mainPanel.add(cancelButton, gbc);
界面的效果是在一个背景图的中间偏右下角的地方,每一行放置一个文本输入,分别用作帐号和密码的输入,第3行放置两个按钮,确定和取消,因为背景图上写好了“用户名”和“密码”这几个字,所以我的两个TextField必须要分别的紧跟着这几个字的后面,现在布局基本没什么问题,但是我想把输入用户名和密码的TextField的长度给缩短点,我用
username.setPreferredSize(new Dimension(100, 10));和setSize函数都不行,username的长度一点变化都没有。反倒是宽值可以跟随数值变化,正在学GridBagLayout的布局。谢谢了。