How to align these JComponents like a Form on center of the Content pane...using Swing
panel1.add(l1);
panel1.add(c1);
panel1.add(l2);
panel1.add(c2);
panel1.add(b4);
panel1.add(b5);
frame1.getContentPane().add(panel1);
Please help me
How about you read the Laying Out Components Within a Container tutorial first? I abuse this saying but, there's always more than one way to skin a cat
Here's a superfluous example that uses BoxLayout
and setAlignmentX(...)
on the JComponent
instances -
public final class StackComponentsDemo {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(new DisabledJButton());
panel.add(new DisabledJButton());
panel.add(new DisabledJButton());
panel.add(new DisabledJButton());
panel.add(new DisabledJButton());
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static final class DisabledJButton extends JButton{
public DisabledJButton(){
super("Disabled");
setEnabled(false);
setAlignmentX(Component.CENTER_ALIGNMENT);
}
}
}
Check SpringLayout if it fits your needs. If not, probably GridBagLayout will do.
Here's an example of using SpringLayout for simple form-like layout.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With