Java – Can you maintain the position of objects on a Java Swing panel

javaswing

I am currently desigining a calculator panel using Java Swing. However, it's an extreme PAIN to line up all of the buttons because they are always resizing and repositioning themseleves whenever I add a new button or change the size of a button.

Is there a type of layout or something that can "lock" the buttons in position so they are not affected when I move/resize/add other buttons?

Thanks,
Bob

Best Solution

Extending what Tom said...

To allow a component to become invisible yet hold its place, you can place it in a CardLayout along with an empty label and just swap which is visible.

You can create a class to do this for you as follows The main just shows an example where if you click a button it's deleted while retaining its position. I put in showComponent/hideComponent and setVisible(t/f) - depends on the style you like.

This might not exactly answer what you're looking for, but might be a useful piece for part of your application.

public class Placeholder extends JPanel {
    private static final long serialVersionUID = 1L;
    private CardLayout cardLayout_;
    public Placeholder(JComponent component) {
        cardLayout_ = new CardLayout();
        setLayout(cardLayout_);
        add(component, "visible"); // the component
        add(new JLabel(), "hidden"); // empty label
    }
    public void showComponent() {
        cardLayout_.show(this, "visible"); 
    }
    public void hideComponent() {
        cardLayout_.show(this, "hidden"); 
    }
    public void setComponentVisible(boolean visible) {
        if (visible)
            showComponent();
        else
            hideComponent();
    }
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setLayout(new GridLayout(2,0));
        for (int n = 1; n < 10; n++) {
            JButton b = new JButton(n + "");
            final Placeholder placeholder = new Placeholder(b);
            f.add(placeholder);
            b.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    placeholder.hideComponent();
                }
            });
        }
        f.pack();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}