簡體   English   中英

如何將 JLabels 和 JPanel 對齊到 BoxLayout 內的左側?

[英]How to align JLabels and JPanels to the left inside BoxLayout?

我想在垂直 BoxLayout 內將標簽和面板(包含按鈕)對齊到左側。

只要我不將面板添加到 BoxLayout 中,所有內容都會完美地向左對齊,但是添加它會將所有內容都搞砸。

import javax.swing.*;
import java.awt.*;

public class BoxLayoutDemo{

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        JPanel five = new JPanel();
        JButton plus = new JButton("+");
        JButton minus = new JButton("-");

        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        Font testFont = new Font("Arial", Font.BOLD, 20);
        JLabel label1 = new JLabel("Label1");
        label1.setFont(testFont);
        JLabel label2 = new JLabel("Label2");
        label2.setFont(testFont);

        five.setLayout(new BoxLayout(five, BoxLayout.X_AXIS));

        plus.setMinimumSize(new Dimension(30, 30));
        plus.setMaximumSize(new Dimension(30, 30));

        minus.setMinimumSize(new Dimension(30, 30));
        minus.setMaximumSize(new Dimension(30, 30));

        five.add(plus);
        five.add(minus);

        panel.add(label1);
        panel.add(five);
        panel.add(label2);

        panel.setOpaque(true);
        panel.setBackground(Color.red);

        frame.setMinimumSize(new Dimension(200, 200));
        frame.getContentPane().add(panel, BorderLayout.EAST);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

    }
}

這就是它的樣子這就是它的樣子

您的組件需要具有相同的“x 對齊”:

label1.setAlignmentX(Component.LEFT_ALIGNMENT);
label2.setAlignmentX(Component.LEFT_ALIGNMENT);
five.setAlignmentX(Component.LEFT_ALIGNMENT);

閱讀 Swing 教程中有關修復 Alignment 問題的部分以獲取更多信息。

您可以使用不可見的組件作為填充物

private static Box leftAlignedInHorizontalBox(Component component) {
    Box box = Box.createHorizontalBox();
    box.add(component);
    box.add(Box.createHorizontalGlue());
    return box;
}

接着:

panel.add(leftAlignedInHorizontalBox(label1));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM