简体   繁体   English

将JComponents与JPanel的左侧和右侧对齐

[英]Aligning JComponents to left- and right-hand sides of a JPanel

I have a JPanel that contains two JComponents, say two JButtons, btnLeft and btnRight. 我有一个包含两个JComponents的JPanel,比如两个JButton,btnLeft和btnRight。 I want these two buttons aligned horizontally and I want btnLeft to be on the left side of the JPanel and btnRight to be on the right side of the JPanel with whatever space is left over in between. 我希望这两个按钮水平对齐,我希望btnLeft位于JPanel的左侧,而btnRight位于JPanel的右侧,两者之间留有任何空间。

I know I can do this with a BoxLayout by adding a horizontal strut in which I have to specify the amount of space in between , but there must be a simpler way without having to specify what the left-over space in between is. 我知道我可以通过添加一个水平支柱 BoxLayout中做到这一点,我必须在其中指定其间的空间量 ,但必须有一个更简单的方法,而不必指定其间的剩余空间。

How do I do this? 我该怎么做呢?

Sounds like horizontalGlue is what you are looking for: 听起来像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"));

If you don't mind vertically stretched buttons, why not to try: 如果您不介意垂直拉伸按钮,为什么不尝试:

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();
    }
}

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM