JButton和JLabel彼此相邻

时间:2016-03-04 14:05:44

标签: java swing layout-manager

我想让JLabelJButton彼此相邻,在下一行中有另一个Jlaben,在下一行中有一个JButton中心。

leftPanel是350宽。

第一个JButtonImageIcon,应位于右上角,该图片为25x25。

此代码返回一个面板,然后显示

JPanel leftPanel = JPanel();

leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));

JLabel userLabel = new JLabel();
userLabel.setPreferredSize(new Dimension(170, 25));
userLabel.setMaximumSize(new Dimension(170, 25));
leftPanel.add(userLabel);

// class that creats a JButton with an ImageIcon and removes border
JButton updateButton = DefaultLayouts.imageButton(new ImageIcon("src/ressources/images/icons/update.png"));
updateButton.setPreferredSize(new Dimension(170, 25));
updateButton.setMaximumSize(new Dimension(170, 25));

leftPanel.add(updateButton);

timeStampLabel.setPreferredSize(new Dimension(350, 25));
timeStampLabel.setMaximumSize(new Dimension(350, 25));
leftPanel.add(timeStampLabel);

unlockButton = DefaultLayouts.imageButton(new ImageIcon("src/ressources/images/icons/unlock.png"));
unlockButton.setPreferredSize(new Dimension(350, 25));
unlockButton.setMaximumSize(new Dimension(350, 25));

leftPanel.add(unlockButton);

panel.add(leftPanel();

现在它只是在中心,我不知道如何处理蓝色按钮。 image

更新代码:

JPanel panel = DefaultLayouts.panel();
panel.setLayout(new GridLayout(0, 2));

JPanel leftPanel = DefaultLayouts.marginPanel(0, 10, 0, 10);
leftPanel.setLayout(new GridBagLayout());

GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;

gridBagConstraints.gridwidth = 2;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
leftPanel.add(userLabel, gridBagConstraints);

JButton updateButton = DefaultLayouts.imageButton(new ImageIcon("src/ressources/images/icons/update.png"));
gridBagConstraints.gridwidth = 1;
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
leftPanel.add(updateButton, gridBagConstraints);

gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
leftPanel.add(timeStampLabel, gridBagConstraints);

unlockButton = DefaultLayouts.imageButton(new ImageIcon("src/ressources/images/icons/unlock.png"));
gridBagConstraints.gridwidth = 3;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
leftPanel.add(unlockButton, gridBagConstraints);

panel.add(leftPanel);

1 个答案:

答案 0 :(得分:0)

您可以使用FlowLayout或GridLayout。

JPanel panel = new JPanel();

panel.setLayout(new FlowLayout());
//or panel.setLayout(new GridLayout(rows, cols));

panel.add(new JLabel("Label"));
panel.add(new JButton("Click"));