Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aligning JButton to the right

I am creating an interface in java and i want to align the button to the right. I have try but its not working. Can someone tell me how to do it?

import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class Button_Alignment extends JFrame{
    public JPanel header,body,footer;
    public JButton add1;
    public JButton save;
    public Button_Alignment(){
        super("BUTTON");
        GridLayout g1 = new GridLayout(3,1);
        setLayout(g1);
        //////
        header = new JPanel();
        JButton add1 = new JButton("add");
        header.add(add1);
        JButton save = new JButton("save");
        header.add(save);
        //////
        add(header);
        header.setBackground(Color.cyan);
    }
    public static void main(String[] args){
        Button_Alignment ba = new Button_Alignment();
        ba.setSize(400, 400);
        ba.setVisible(true);
    }
}
like image 378
Ravi77 Avatar asked Nov 04 '25 12:11

Ravi77


1 Answers

Your current layout manager (GridLayout) is being created with 3 rows and a single column. Hence, the components you add to the JFrame will appear vertically from top to bottom. Worse still, GridLayout will aportion space equally amongst all 3 components, meaning that your buttons will stretch in both directions, which is almost certainly not what you require.

I would consider using an alternative layout manager. For simple layouts I tend to favour BorderLayout or FlowLayout. For more complex layouts I lean towards GridBagLayout although there are others who prefer MigLayout.

More information here.

like image 180
Adamski Avatar answered Nov 06 '25 02:11

Adamski