首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >BoxLayout中的Java Swing对齐问题

BoxLayout中的Java Swing对齐问题
EN

Stack Overflow用户
提问于 2021-09-28 09:46:36
回答 1查看 52关注 0票数 0

我在一个自上而下的boxLayout中有三个组件(JLabel、JTextField、JButton)。问题是,当我为标签设置X对齐时,它看起来好像我已经改变了按钮的X对齐,反之亦然,只有当两者都有相同的对齐方式时,它才能正常工作。

当屏幕变宽时,两个组件都会出现奇怪的对齐方式。

当两个组件具有相同的对齐方式时,一切工作正常。

下面是我的代码:

代码语言:javascript
运行
复制
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);
}
EN

回答 1

Stack Overflow用户

发布于 2021-09-28 10:35:25

以下是Andrew Thompson提出的解决方案:

代码语言:javascript
运行
复制
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);
    }

}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69359417

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档