我正在尝试构建一组两个标签和一个按钮(标签-按钮-标签),看起来像这样的顶行:
.
我正在努力用 Java Swing 做到这一点。我已经尝试过 BorderLayout,使用 BorderLayout.WEST、BorderLayout.CENTER、BorderLayout.EAST 但这会使按钮填充空间:
这是我用于此的代码:
panel = new JPanel(new BorderLayout());
l1 = new JLabel("l1");
button = new JButton("B");
l2 = new JLabel("l2");
panel.add(l1, BorderLayout.WEST);
panel.add(button, BorderLayout.CENTER);
panel.add(l2, BorderLayout.EAST);
我也尝试过 GridBagLayout,我最接近的是将它们分开,但不拥抱两侧:
代码:
panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.VERTICAL;
l1 = new JLabel("L1");
l2 = new JLabel("L2");
button = new JButton("B");
c.weightx = Integer.MAX_VALUE;
c.gridx = 0;
panel.add(l1, c);
c.weightx = 1;
c.gridx = 1;
panel.add(button, c);
c.weightx = Integer.MAX_VALUE;
c.gridx = 2;
panel.add(l2, c);
有任何想法吗?