为什么BoxLayout不允许我改变JButton的宽度但让我改变高度?

Bra*_*uck 18 java user-interface swing jpanel jbutton

我正在尝试使用我的一个布局JDialog以适应我正在移植到Java的程序的特定外观,我之前使用过几个LayoutManagers并取得了巨大的成功但由于某种原因我似乎无法得到这个工作在一起.我的目标是让内部的右侧(东侧)JDialog按照自上而下的顺序包含"查找下一个"和"取消"按钮,然后在下面的任何额外空间中,以便两个按钮始终位于顶部JDialog,出于某种原因BoxLayout不断忽视任何改变的尝试(这是我失去的地方)的宽度JButton.代码如下.

JButton findNext = new JButton("Find Next");
JButton cancel = new JButton("Cancel");
cancel.setPreferredSize(new Dimension((int)findNext.getPreferredSize().getWidth(),  
    (int)cancel.getPreferredSize().getHeight()));

JPanel example = new JPanel();  
example.setLayout(new BoxLayout(example, BoxLayout.Y_AXIS));  
example.add(findNext);
example.add(cancel);  
example.add(Box.createGlue());  
Run Code Online (Sandbox Code Playgroud)

无论我尝试什么,cancel始终保持它的正常尺寸.我已经尝试setMinimumSize()setMaximumSize()使用相同的参数setPreferredSize,没有运气.我甚至尝试cancel.setPreferredSize(new Dimension(500, 500));了按钮高度是唯一调整的东西,它仍然保留了它给出的默认宽度.

要清除任何问题,这就是它的样子(现在我已经完成了),你会看到"查找下一个"和"取消"按钮的大小不同.

示例图片

Mic*_*ael 47

我知道这是一个老问题,但我没有看到一个很好的解释.因此,为了找到偶然发现的搜索者,我将加上我的两分钱.

在Swing中调整组件大小有三种方法:setPreferredSize(),setMinimumSize()和setMaximumSize().但是,重要的一点是,它取决于特定的布局管理器是否遵循这些方法中的任何一种.

对于BoxLayout(原始海报使用的布局):

  • setMinimumSize() - BoxLayout尊重这一点
  • setMaximumSize() - BoxLayout尊重这一点
  • setPreferredSize() - 如果正在使用X_AXIS,则使用宽度,如果正在使用Y_AXIS,则高度受到尊重

OP正在使用Y_AXIS BoxLayout,这就是为什么他的身高只会被改变.

更新:我为所有布局管理器整理了一个包含相同信息的页面.希望它可以帮助一些搜索者:http://thebadprogrammer.com/swing-layout-manager-sizing/


tra*_*god 6

你可能不想要Box.createGlue()," 根据需要增长以吸收其容器中的任何额外空间." 而是在按钮之间使用,如下所示和此模拟中所示.Box.createVerticalStrut() ControlPanel

example.setLayout(new BoxLayout(example, BoxLayout.Y_AXIS));
example.add(findNext);
Box.createVerticalStrut(10);
example.add(cancel);
Run Code Online (Sandbox Code Playgroud)

附录:

加入setMaximumSize()使它工作.

这是垂直中具有相同最大宽度的组件的预期行为BoxLayout,如框布局特征中所述.容器的首选宽度变为(同样宽的)子容器的宽度,并且X对齐变得无关紧要.

example.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JButton findNext = new JButton("Find Next");
JButton cancel = new JButton("Cancel");
Dimension d = findNext.getMaximumSize();
cancel.setMaximumSize(new Dimension(d));
example.add(findNext);
example.add(cancel);
Run Code Online (Sandbox Code Playgroud)