user157629
user157629

Reputation: 634

How can I align one element to the right and another to the left side of my JPanel?

I created a JPanel and added two JButtons in it. I set the panel layout as FlowLayout. I want one JButton to be on the left of the JFrame and the other JButton to be on the right.

I tried this but it's throwing an IllegalArgumentException:

        JPanel mainPanel = new JPanel(new FlowLayout());

        JButton login = new JButton("Login");
        JButton register = new JButton("Register");

        mainPanel.add(register, FlowLayout.RIGHT);
        mainPanel.add(login, FlowLayout.LEFT);

Can I do this using FlowLayout? Which layout would make it work?

Upvotes: 0

Views: 793

Answers (1)

camickr
camickr

Reputation: 324197

mainPanel.add(register, FlowLayout.RIGHT);
mainPanel.add(login, FlowLayout.LEFT);

That is not how those FlowLayout variables are used. They are used as properties of the layout manager, not as a constraint for the add(…) method. Read the FlowLayout API for more information.

I want one JButton to be on the left of the JFrame and the other JButton to be on the right. Can I do this using FlowLayout?

No.

Which layout would make it work?

You could use a panel with a:

  1. BorderLayout - add one button to the BorderLayout.LINE_START and one to the BorderLayout.LINE_END
  2. BoxLayout - add a Box.createHorizontalGlue() between the two buttons.

Read the section from the Swing tutorial on Layout Managers for more information and examples on each of the above layout managers.

Upvotes: 1

Related Questions