user1775500
user1775500

Reputation: 2423

How to align two JButtons to be right aligned?

So currently my program shows only one of the buttons in the bottom right hand of the GUI. But I want to show both buttons in the bottom right hand corner. Any ideas how to set both buttons to the right corner? Here is my code so far:

import javax.swing.*;

import java.awt.*;

public class Other extends JFrame{
        private static final long serialVersionUID = 1L;
        public Other() {
            super("Buttons");
            final Container mainPanel = getContentPane();
            mainPanel.setLayout(new BorderLayout());
            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout(new BorderLayout());
            JPanel inputPanel = new JPanel();
            inputPanel.add(new JLabel("RANDOM TEXT HERE"));
            inputPanel.add(new JLabel("RANDOM TEXT HERE"));
            inputPanel.add(new JLabel("RANDOM TEXT HERE"));
            JButton s = new JButton("first");
            JButton l = new JButton("second");
            buttonPanel.add(s,BorderLayout.LINE_END);
            buttonPanel.add(l,BorderLayout.LINE_END); //<-- not working
            mainPanel.add(inputPanel,BorderLayout.PAGE_START);
            mainPanel.add(buttonPanel,BorderLayout.PAGE_END);
            pack();
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setLocationRelativeTo(null);
            setVisible(true);
        }
   public static void main(String[] args){
       Other o = new Other();
   }
}

Upvotes: 3

Views: 3463

Answers (2)

Gowtham Ravichandran
Gowtham Ravichandran

Reputation: 15

you can design GUI better and easy with Netbeans 7.1 .. you can align the swing components wherever you like and even make dependent on size of the frame ... you can get it here https://netbeans.org/downloads/index.html

Upvotes: 0

Andrew Thompson
Andrew Thompson

Reputation: 168815

enter image description here

buttonPanel.setLayout(new FlowLayout(FlowLayout.TRAILING));

While the BorderLayout will only accept one component per layout area, FlowLayout will display as many as are added (within viewable bounds).

Upvotes: 7

Related Questions