2017-08-25 148 views
0

我正尝试使用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为背景。

这是为什么?我怎样才能对齐左侧的按钮?

回答

1

我设置对齐到左,但我的按钮都集中

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

默认情况下,JPanel使用FlowLayout。在创建FlowLayout时,默认情况下,添加到面板的组件在面板空间中为centered aligned

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

此外,您可以提供按钮之间的默认间隔,所以不需要Box.createRigidArea(...)。当您使用BoxLayout时,该组件确实用于使用。

+0

你说的工作,但即时通讯与背景图像相同的问题,你能否告诉我一种方法来设置它。 – carelli99

+0

和我可以使用setVgap与我的代码? – carelli99

相关问题