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);
}
}
Your current layout manager (
GridLayout) is being created with 3 rows and a single column. Hence, the components you add to theJFramewill appear vertically from top to bottom. Worse still,GridLayoutwill 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
BorderLayoutorFlowLayout. For more complex layouts I lean towardsGridBagLayoutalthough there are others who preferMigLayout.More information here.