BoxLayout不能将单个元素与奇数宽度对齐到中心

时间:2014-05-03 01:40:49

标签: java swing user-interface layout-manager boxlayout

我试图沿着面板中心的垂直轴对齐多个元素,BoxLayout似乎正是我需要的。然而,当添加的所有元素都具有奇数宽度时,似乎做了一些奇怪的事情。

这是一个证明这种棘手行为的SSCCE:

import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.JFrame;
import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.BoxLayout;
import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.Color;
import java.awt.Component;

public class BoxBug {
  public static void main(String[] args){
    UIManager.put("swing.boldMetal", Boolean.FALSE);
    SwingUtilities.invokeLater(new Runnable(){
      public void run(){
        gui();
      }
    });
  }

  public static void gui(){
    JFrame f = new JFrame("Title");
    Box b = new Box(BoxLayout.Y_AXIS);

    JComponent c = new JComponent(){
      public void paint(Graphics g){
        g.setColor(new Color(255, 0, 0));
        g.fillRect(0, 0, getWidth(), getHeight());
      }

      // just change the first argument here
      // (even numbers work fine, odd ones fail)
      private Dimension p = new Dimension(3, 20);
      public Dimension getPreferredSize(){return p;}
      public Dimension getMinimumSize(){return p;}
      public Dimension getMaximumSize(){return p;}
    };
    c.setAlignmentX(Component.CENTER_ALIGNMENT);

    b.add(c);
    f.add(b);
    f.pack();
    f.setVisible(true);
  }
}

这就是它的样子:

enter image description here

当我将JComponent的宽度从3更改为4时,它可以正常工作:

enter image description here

然后当我将宽度更改为5时,它再次失败:

enter image description here

我已经在谷歌和StackOverflow上搜索了这个问题,但是没有找到任何关于此问题的文档,所以在我看来它就像一个错误。

如果它是一个错误,有人可以找到一个黑客来解决它吗?

1 个答案:

答案 0 :(得分:1)

  

然而,当添加的所有元素都具有奇数宽度时,它似乎做了一些奇怪的事情。

比这更奇怪。父容器的大小也会影响布局。

我用:

替换了f.pack()
f.setSize(150, 100);

它不起作用。这基本上是您描述的场景,因为此方法或f.pack()将导致父容器具有偶数宽度并且布局不起作用。

但是,如果您使用:

f.setSize(151, 100);

父容器的宽度为奇数,布局可以正常工作。

另一个奇怪的观察。我尝试在Box中添加多个组件。当添加的最后一个组件具有奇数宽度时,似乎只会发生这个问题。

无论如何,我不知道盒子布局在做什么,但对我来说这肯定是个错误。

解决方案是使用不同的布局管理器。您可以使用GridBagLayout显示不同行上的组件。您需要为每个组件设置约束以转到新行。

或者您可以尝试使用Relative Layout,它支持具有居中对齐的垂直布局,您不需要任何约束。对代码的唯一更改是:

//Box b = new Box(BoxLayout.Y_AXIS);
JPanel b = new JPanel( new RelativeLayout(RelativeLayout.Y_AXIS) );