Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing JComponents alignment like form

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

like image 313
ram Avatar asked Jan 20 '23 00:01

ram


2 Answers

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);
        }
    }
}

enter image description here

like image 194
mre Avatar answered Jan 21 '23 14:01

mre


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.

like image 24
Michał Šrajer Avatar answered Jan 21 '23 13:01

Michał Šrajer