在JScrollPane中为每个组件设置最小高度

时间:2012-04-02 02:05:18

标签: java swing

我是否有任何方法可以确保窗格中的每个按钮都保持最小高度?我尝试使用itembutton.setSize()方法,但它没有效果。

JPanel itemPanel = new JPanel();

itemPanel.setLayout(new GridLayout(0,1));

for(final Item i: list){
    JButton itemButton = new JButton(i.getName());
    itemPanel.add(itemButton);
}

JScrollPane itemPane = new JScrollPane(itemPanel);

1 个答案:

答案 0 :(得分:0)

itembutton.setMinimumSize(minimumSize)

编辑:刚刚发现,正如this java tutorial似乎告诉我们,GridLayout无法做到这一点。

  

每个组件占用其单元格中的所有可用空间,每个单元格的大小完全相同

所以我想你必须尝试另一种布局。我可以建议(不知道它是否适合,但它有效)GridBagLayout。带2个按钮的示例:

itemPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.weightx = 0.5;
itemPanel.add(new JButton("A"), c);
c.gridx = 1;
c.weightx = 0.5;
itemPanel.add(new JButton("B"), c);

查看http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html