- 您应该确保将 GridBagConstraint 的填充属性设置为文本字段的水平,并确保将 weightx 设置为大于 0 的值
- 或者您可以向文本字段指示要显示的所需列数(这最终会影响文本字段的首选大小)。
这是一个示例,表明:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.net.MalformedURLException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestGridBagLayout {
protected void initUI() throws MalformedURLException {
final JFrame frame = new JFrame();
frame.setTitle(TestGridBagLayout.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(new GridBagLayout());
JLabel firstName = new JLabel("First name:");
JLabel lastName = new JLabel("Last name:");
JTextField firstNameTF = new JTextField();
JTextField lastNameTF = new JTextField();
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(3, 3, 3, 3);
gbc.weightx = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.CENTER;
panel.add(firstName, gbc);
gbc.weightx = 1;
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel.add(firstNameTF, gbc);
gbc.gridwidth = 1;
gbc.weightx = 0;
panel.add(lastName, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
panel.add(lastNameTF, gbc);
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
new TestGridBagLayout().initUI();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
}