0

我有一个这样的JPanel:

GridBagConstraints constPanelInfo = new GridBagConstraints();
    panelInfo = new JPanel(new GridBagLayout());
    JLabel sensor1 = new JLabel("Sensor: ");
    constPanelInfo.gridx = 0;
    constPanelInfo.gridy = 0;
    constPanelInfo.weightx = 0.0;
    constPanelInfo.fill = GridBagConstraints.NONE;
    panelInfo.add(sensor1, constPanelInfo);
    constPanelInfo.gridx = 1;
    constPanelInfo.gridy = 0;
    constPanelInfo.weightx = 1.0;
    constPanelInfo.fill = GridBagConstraints.HORIZONTAL;
    campoSensor.setPreferredSize(new Dimension(100, campoSensor.getPreferredSize().height));
    panelInfo.add(campoSensor, constPanelInfo);

其中campoSensor定义为:

private JTextField campoSensor = new JTextField();

...但是 JTextField 没有按我的意愿缩放到 100 px 的重量:它保持与编写 setPreferredSize 方法之前相同的大小。这里有什么想法吗?

4

2 回答 2

0

尝试设置constPanelInfo.iPadX=100;而不是设置首选大小。

于 2011-06-22T09:59:12.357 回答
0

希望这是您正在寻找的...设置

constPanelInfo.weightx = 0;

传感器应保持在指定的 100 像素。即如果所有的权重都为零,则所有多余的空间都出现在单元格的网格与左右边缘之间。

请记住,如果设置了权重并且由于

constPanelInfo.fill = GridBagConstraints.HORIZONTAL;

无论首选大小如何,campoSensor 都将填充单元格的整个宽度。这个宽度可能由面板所在的 JFrame 的大小决定。

于 2011-06-22T10:30:02.487 回答