【问题标题】:How to right-justify a component within a SpringLayout?如何在 SpringLayout 中右对齐组件?
【发布时间】:2012-12-04 00:51:29
【问题描述】:

我正在尝试创建一个左侧有几个文本项,右侧有一个按钮的布局。我已经完全按照我想要的方式获得了文本项,但我无法让按钮在右侧对齐。

我正在按如下方式创建按钮:

    SpringLayout layout = new SpringLayout();
    JPanel p2 = new JPanel(layout);
    // set panel size very large so it fills its own parent
    p2.setMaximumSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE));
    p2.setBackground(new Color(0xffd0d0));
    p2.setBorder(BorderFactory.createLineBorder(new Color(0)));
    // Add some text items; omitted for clarity
    ...
    // Add a button in the lower-right corner
    JButton btn = new JButton(refreshAction);
    p2.add(btn);
    layout.putConstraint(SpringLayout.EAST, btn,
                Spring.constant(0),
                SpringLayout.EAST, p2);
    layout.putConstraint(SpringLayout.SOUTH, btn,
                Spring.constant(0),
                SpringLayout.SOUTH, p2);

我认为这会将按钮的东边和南边与容器的东边和南边对齐,但它没有发生。看起来按钮边缘与容器的首选大小而不是其实际大小对齐。

另一个数据点:当我设置标签的值时,按钮会跳到右边,与刚刚添加的文本的末尾对齐。显然,容器的首选大小已经增加,即使实际大小没有改变,并且按钮的位置也随之改变。

【问题讨论】:

    标签: java swing springlayout


    【解决方案1】:

    好吧,两天后没有答案 = 找到另一种方法。我最终使用了 GridBagLayout,我一开始就应该这样做。我会留下这个问题,以防有一天有人回答。

    【讨论】:

      【解决方案2】:

      所以这是一个非常古老的问题,但我在使用 SpringLayout 进行右对齐时遇到了类似的问题。

      对我有用的是从左侧对齐事物,并调整组件的大小以适应面板的右边缘。 (这可能不是最好的解决方案)

      例如,如果我有四个要对齐的框:

      |盒子1 |盒子2 |

      |盒子3 |盒子4 |

      box1 将是:

      layout.putConstraint(SpringLayout.NORTH, box1, 2, SpringLayout.NORTH, buttonPanel);
      layout.putConstraint(SpringLayout.WEST, box1, 2, SpringLayout.WEST, buttonPanel);
      

      box2 将是:

      layout.putConstraint(SpringLayout.NORTH, box2, 2, SpringLayout.NORTH, buttonPanel);
      layout.putConstraint(SpringLayout.WEST, box1, 2, SpringLayout.EAST, box1);
      

      box3 将是:

      layout.putConstraint(SpringLayout.NORTH, box3, 2, SpringLayout.SOUTH, box1);
      layout.putConstraint(SpringLayout.WEST, box3, 2, SpringLayout.WEST, buttonPanel);
      

      box4 将是:

      layout.putConstraint(SpringLayout.NORTH, box4, 2, SpringLayout.SOUTH, box2);
      layout.putConstraint(SpringLayout.WEST, box1, 2, SpringLayout.EAST, box3);
      

      【讨论】:

      • 看起来它会将所有箱子都装在集装箱的西北角。我想要的是 box4 坐在容器的右边缘,即使容器比容纳盒子所需的大。
      猜你喜欢
      • 2014-03-04
      • 2012-08-19
      • 2015-11-24
      • 1970-01-01
      • 2016-05-06
      • 2017-12-22
      • 2018-03-09
      • 2019-06-15
      • 1970-01-01
      相关资源
      最近更新 更多