首页 > 解决方案 > BoxLayout 的 Java Swing 对齐问题

问题描述

我在一个从上到下的 boxLayout 内有三个组件(JLabel、JTextField、JButton)。问题是,当我为标签设置 X 对齐时,它看起来好像我会更改按钮的 X 对齐,反之亦然,只有当两者具有相同的对齐时它才能正常工作。

当屏幕变宽时,两个组件都会出现奇怪的对齐方式。 在此处输入图像描述

当两个组件具有相同的对齐方式时,一切正常。 在此处输入图像描述

这是我的代码:

public void create(){
    JPanel panel =  new JPanel();
    BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.Y_AXIS);
    panel.setLayout(boxLayout);
    panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
    
    JLabel etiqueta =  new JLabel("Numero de consultorio: ");
    etiqueta.setBackground(Color.BLUE);
    etiqueta.setOpaque(true);
    etiqueta.setAlignmentX(Component.LEFT_ALIGNMENT);
    panel.add(etiqueta);
    
    JTextField consultorio = new JTextField();
    panel.add(consultorio);
    
    JButton registrar =  new JButton("Registrar");
    registrar.setAlignmentX(Component.LEFT_ALIGNMENT);
    panel.add(registrar);
    
    this.getContentPane().add(panel, BorderLayout.CENTER);
}

标签: javaswingalignmentlayout-managerboxlayout

解决方案


这是 Andrew Thompson 提出的解决方案:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class TestFrame {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new TestFrame()::create);
    }

    private void create() {
        JPanel panel = new JPanel();
        BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.Y_AXIS);
        panel.setLayout(boxLayout);
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JLabel etiqueta = new JLabel("Numero de consultorio: ");
        etiqueta.setBackground(Color.BLUE);
        etiqueta.setOpaque(true);
        JPanel layout = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
        layout.add(etiqueta);
        panel.add(layout);

        JTextField consultorio = new JTextField();
        panel.add(consultorio);

        JButton registrar = new JButton("Registrar");
        layout = new JPanel(new FlowLayout(FlowLayout.TRAILING, 0, 0));
        layout.add(registrar);
        panel.add(layout);

        JFrame frm = new JFrame("Test");
        frm.getContentPane().add(panel, BorderLayout.CENTER);
        frm.pack();
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }

}

推荐阅读