繁体   English   中英

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

[英]Buttons are set to be left-aligned but are still displayed as centered

我正在尝试使用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);
    }
}

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

在此处输入图片说明

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

为什么是这样? 如何对齐左侧的按钮?

我将“对齐方式”设置为左侧,但按钮居中

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

默认情况下,JPanel使用FlowLayout 同样,在默认情况下,当您创建FlowLayout ,添加到面板中的组件在面板空间中centered aligned

将布局管理器更改为FlowLayout ,使组件left aligned 阅读FlowLayout API,以使用适当的构造函数。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM