Aligning JButton to the right
Solution 1
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.
Solution 2
Try like this:
JButton save = new JButton ("save");
setLayout (new BorderLayout ());
add (save, BorderLayout.EAST);
Ravi77
Updated on June 04, 2022Comments
-
Ravi77 almost 2 years
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); } }