如何填充JToolbar中的空白区域

时间:2012-07-30 21:12:33

标签: java swing

我的某个面板中有 JToolbar

简化代码:

//for the containing panel
panel.setLayout(new BorderLayout());


//adding the toolbar
panel.add(toolbar, BorderLayout.WEST);

工具栏有两个JButton,我使用GridBagLayout添加它们以使它们具有相等的宽度

//工具栏的代码

toolbar=new JToolbar();
toolbar.setLayout(new GridBagLayout());
btn1 = new JBUtton("update layout");
btn2 = new JButton("exit!");
GridBagContraints gbc = new GridBagConstraints();
gbc.gridx=0;
gbc.gridy=1;
gbc.fill = GridBagConstrainsts.HORIZONTAL;
toolbar.add(btn1,gbc);
gbc.gridy=1;
toolbar.add(btn1,gbc);

此代码呈现带有按钮的垂直工具栏,宽度相等。唯一的问题是工具栏的高度大于按钮的高度,因此该代码将按钮呈现在工具栏的垂直中心。相反,我希望按钮与顶部对齐,以便将所有空白空间添加到工具栏的末尾。

现在:

 ----------
 |        |
 ----------
 |  btn   |
 ----------
 |  btn2  |
 ----------
 |        |
 ----------

我想要什么

 ----------
 |   btn  |
 ----------
 |   btn2 |
 ----------
 |        |
 ----------
 |        |
 ----------

2 个答案:

答案 0 :(得分:0)

我认为您只需在工具栏中添加Box.createVerticalGlue(),而无需将布局更改为GridBagLayout。这将填满按钮后的剩余空间并将它们推到顶部。

答案 1 :(得分:0)

有点像复活死者。但是我遇到了一个非常相似的问题并找到了解决方案,所以为什么不共享它:

您必须为按钮设置最大尺寸,否则最大尺寸由ButtonUI计算。并将setHorizo​​ntalAlignment设置为SwingConstants.RIGHT以使按钮内容对齐:

public class JToolBarPractise extends JFrame {

  public JToolBarPractise() {
    super();
    addWindowListener(new WindowAdapter() {

      public void windowClosing(WindowEvent we) {
        System.exit(0);
      }
    });
    JPanel contentPanel = new JPanel(new BorderLayout());
    JToolBar toolBar = new JToolBar(SwingConstants.VERTICAL);
    JButton button1 = new JButton("Update Layout!");
    button1.setHorizontalAlignment(SwingConstants.RIGHT);
    button1.setMaximumSize(new Dimension(Short.MAX_VALUE, button1.getPreferredSize().height));
    toolBar.add(button1);
    JButton button2 = new JButton("Exit!");
    button2.setHorizontalAlignment(SwingConstants.RIGHT);
    button2.setMaximumSize(new Dimension(Short.MAX_VALUE, button2.getPreferredSize().height));
    button2.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent ae) {
        System.exit(0);
      }
    });
    toolBar.add(button2);
    contentPanel.add(toolBar, BorderLayout.WEST);
    getContentPane().add(contentPanel);
  }

  public static void main(String[] args) throws ClassNotFoundException, InstantiationException,
    IllegalAccessException, UnsupportedLookAndFeelException {
    JToolBarPractise main = new JToolBarPractise();
    main.setSize(300, 300);
    main.setVisible(true);
  }
}