我正面临 Java GridBagLayout 的问题。
运行以下代码:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main extends JFrame{
public static void main (String [] args){
new Main();
}
public Main(){
add(getPanel());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setSize(600, 150);
}
private JPanel getPanel(){
JPanel panel = new JPanel(new GridBagLayout());
JLabel label1 = new JLabel("Label 1");
JLabel label2 = new JLabel("Label 2");
JLabel label3 = new JLabel("Label 3");
JTextField area1 = new JTextField();
JTextField area2 = new JTextField();
JComboBox<String> box = new JComboBox<String>();
box.addItem("One One One");
box.addItem("Two Two Two");
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 10, 10, 10);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0;
panel.add(label1, gbc);
gbc.gridx = 1;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(area1, gbc);
gbc.gridx = 2;
gbc.weightx = 0;
gbc.fill = GridBagConstraints.NONE;
panel.add(label2, gbc);
gbc.gridx = 3;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(area2, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
panel.add(label3, gbc);
gbc.weightx = 1;
gbc.gridx = 1;
panel.add(box, gbc);
return panel;
}
}
产生以下窗口:
但是这两个 JTextField 应该是相同的宽度。
如果我不添加 JComboBox 一切都很好:
我的问题是:为什么最后一个组件会影响前面组件的网格宽度?对我来说真正奇怪的是,如果 JComboBox 长度增加,正确的 JTextField 会变小。实际上看起来左侧 JTextField 的长度等于右侧 JTextField 的长度 + JComboBox 的长度。在下一行有两个长度相等的文本字段和一个 JComboBox 的诀窍是什么?
提前致谢!