java - 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);
}
解决方案
这是 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);
}
}
推荐阅读
- php - 使用 php 选择一些 csv 值以导出到 html 表中
- java - 使用路由数据源和 JdbcTemplate 启动多个数据库事务
- linux - 关于 TMP_DIR 空间使用并行程序的错误
- angular - Nx Workspace - 我如何将 Angular 项目作为 https 服务
- c - 14字节数据的加密算法
- database - 使用“公共”模式连接到 PostgreSQL 数据库
- vba - 是否可以以编程方式单击关闭按钮
- angular - 如何以角度访问父函数?
- python - Pyspark 使用 2 个数据帧中的值和阈值生成段数组
- ruby-on-rails - Rails API Omniauth