2017-08-25 6 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

関連する問題