Why will BoxLayout not allow me to change the width of a JButton but let me change the height?

前端 未结 6 1827
别那么骄傲
别那么骄傲 2020-12-31 01:49

I\'m trying to get the Layout of a JDialog of mine to fit a particular look that a program in which I\'m porting to Java has, I\'ve used several LayoutManagers

6条回答
  •  独厮守ぢ
    2020-12-31 02:39

    As mentioned in the comments on the question, you were able to fix it by switching to setMaximumSize(). However, as you noted, setPreferredSize() doesn't work. So, what's up with that?

    With many things Swing, the properties used to determine the actual component size when using the BoxLayout are somewhat random (in my opinion). When determining how to render the components, Swing calls layoutComponent() on the layout manager, which is figures out where to position everything.

    BoxLayout's implementation of layoutComponent() involves a call to a method that creates SizeRequirements objects for the width and height of each of the components you add to the JPanel, based on their getMinimum/Preferred/MaximumSize() methods.

    Later, it calls SizeRequirements.calculateAlignedPositions() for determining the correct width values for each component, because your orientation is BoxLayout.Y_AXIS (The heights are calculated using a different method). Taking snippets from the source, the relevant implementation of this method is as follows:

    for (int i = 0; i < children.length; i++) {
        SizeRequirements req = children[i];
        //...
        int maxAscent = (int)(req.maximum * alignment);
        int maxDescent = req.maximum - maxAscent;
        //...
        int descent = Math.min(totalDescent, maxDescent);
        //...
        spans[i] = (int)Math.min((long) ascent + (long)descent, Integer.MAX_VALUE);
    }
    

    Note that totalDescent is the available width, so descent is always set to maxDescent, which is based on SizeRequirements.maximum, which was taken from JButton.getMaximumSize(). The value of spans[i] is then used later in a call to JButton.setBounds() as the width. As you'll note, getPreferredSize() was never involved here, which is why setting it has no impact in this case.

提交回复
热议问题