java - 按钮设置为左对齐,但仍显示为居中

标签 java swing

我正在尝试使用 Swing 创建一个界面。

这是我的代码:

public class JavaApplication30 
{
    public static void main(String[] args) throws IOException 
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.X_AXIS));
        frame.setPreferredSize(new Dimension(1280, 720));
        frame.setResizable(false);

        frame.setContentPane(new JPanel() 
        {
        BufferedImage image = ImageIO.read(new File("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaApplication29\\src\\eila.jpg"));
        @Override
        public void paintComponent(Graphics g) 
        {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, 1280, 720, this);
        }
        });

        JPanel a = new JPanel();
        a.setAlignmentX(Component.LEFT_ALIGNMENT);
        a.setPreferredSize(new Dimension(150, 500));
        a.setMaximumSize(new Dimension(150, 500));
        a.setOpaque(false);

        a.add(Box.createRigidArea(new Dimension(5,50)));
        JButton amico = new JButton("Amico");
        a.add(amico);
        a.add(Box.createRigidArea(new Dimension(5,20)));
        amico.setPreferredSize(new Dimension(150, 50));
        JButton bello = new JButton("Bello");
        a.add(bello);
        a.add(Box.createRigidArea(new Dimension(5,20)));
        bello.setPreferredSize(new Dimension(150, 50));
        JButton compagno = new JButton("Compagno");
        a.add(compagno);
        compagno.setPreferredSize(new Dimension(150, 50));

        frame.getContentPane().add(a);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

class ImagePanel extends JComponent {
    private Image image;
    public ImagePanel(Image image) {
        this.image = image;
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
}

我将按钮对齐设置为左侧,但我的按钮仍然居中。

enter image description here

如果没有paintComponent作为背景,这不会发生。

这是为什么呢?如何将按钮对齐到左侧?

最佳答案

I set Alignment to left, but my buttons are centered

setAlignmentX(...) 只是“面板”应如何在其父面板中对齐的提示。当您将按钮添加到面板时,重要的是面板的布局管理器。

默认情况下,JPanel 使用FlowLayout。另外,默认情况下,当您创建 FlowLayout 时,添加到面板的组件会在面板空间中居中对齐

将布局管理器更改为组件左对齐FlowLayout。阅读 FlowLayout API 以了解要使用的正确构造函数。

此外,您可以在按钮之间提供默认间隙,因此不需要 Box.createRigidArea(...)。该组件实际上是在您使用 BoxLayout 时使用的。

关于java - 按钮设置为左对齐,但仍显示为居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45882250/

相关文章:

java - IllegalArgumentException:创建 SpinnerListModel 时序列元素无效

java - 仅在按下 JButton 时绘画

java - 分发我的 java 应用程序,如何管理目录

java - Hibernate 用 NULL 覆盖列值?

java - 带参数的方法和不带参数的方法之间的区别?

java - 根据另一个列表值的索引对列表进行排序

java - 如何使用 Java 在 Axe-Core 中运行特定标签的可访问性测试

java - 使线程在来自 EDT 的非 EDT(事件调度线程)线程上运行

java - 用于大富翁棋盘游戏的 Java 最佳 GUI 方法

java - 如何阻止 JTextArea 和 JTextField 拉伸(stretch)?