bobbobbob
bobbobbob

Reputation: 92

JButton Set X Location not working

I have a JWindow which has a JLabel and JButton in a JPanel. I'm trying to set the location of the JButton to the center. For some reason, setting the y location works, but the x location doesn't change. What is wrong with my code?

JWindow window = new JWindow();
    JPanel panel = new JPanel();
    panel.setLayout(new OverlayLayout(panel));
    JButton singlePlayer = new JButton("Single Player", new ImageIcon(this.getClass().getResource("ButtonSword.png")));
    singlePlayer.setPreferredSize(new Dimension(170, 50));
    singlePlayer.setLocation(window.getWidth()/2-85, window.getHeight()/2-25);
    JLabel label = new JLabel(new ImageIcon(this.getClass().getResource("Splash.png")));
    panel.add(singlePlayer);
    panel.add(label);
    window.getContentPane().add(panel);
    window.pack();
    window.setLocationRelativeTo(null);
    window.setVisible(true);

Upvotes: 1

Views: 227

Answers (1)

camickr
camickr

Reputation: 324128

If you want to play with the OverlayLayout, then you will also need to make sure that you use:

setAlignmentX(Component.CENTER_ALIGNMENT);
setAlignmentY(Component.CENTER_ALIGNMENT);

for both the label and the player so that the alignments are in sync.

Upvotes: 1

Related Questions