【问题标题】:Aligning JComponents to left- and right-hand sides of a JPanel将 JComponents 与 JPanel 的左侧和右侧对齐
【发布时间】:2012-01-24 15:14:58
【问题描述】:

我有一个 JPanel,它包含两个 JComponent,比如两个 JButton,btnLeft 和 btnRight。我希望这两个按钮水平对齐,并且我希望 btnLeft 位于 JPanel 的左侧,而 btnRight 位于 JPanel 的右侧,中间留有任何空间。

我知道我可以使用 BoxLayout 通过添加一个水平支柱来做到这一点我必须在其中指定之间的空间量,但必须有一个更简单的方法而不必指定什么之间的剩余空间是。

我该怎么做?

【问题讨论】:

    标签: java swing layout jpanel jcomponent


    【解决方案1】:

    听起来horizo​​ntalGlue就是你要找的东西:

        JComponent comp = new JPanel();
        comp.setLayout(new BoxLayout(comp, BoxLayout.LINE_AXIS));
        comp.add(new JLabel("left"));
        comp.add(Box.createHorizontalGlue());
        comp.add(new JLabel("right"));
    

    【讨论】:

      【解决方案2】:

      如果您不介意垂直拉伸按钮,不妨试试:

      import java.awt.BorderLayout;
      
      import javax.swing.JButton;
      import javax.swing.JFrame;
      
      public class JFrame1 {
      public static void main(String[] args) {
              JFrame frame = new JFrame();
              JButton btn1 = new JButton("Btn1");
              JButton btn2 = new JButton("Btn2");
              frame.setLayout(new BorderLayout());
              frame.setSize(500, 400);
              frame.add(btn1, BorderLayout.WEST);
              frame.add(btn2, BorderLayout.EAST);
              frame.show();
          }
      }
      

      【讨论】:

      • 还要考虑EASTWESTFlowLayout中的嵌套布局。
      猜你喜欢
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      • 1970-01-01
      • 2019-04-20
      相关资源
      最近更新 更多