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


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?


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();
        add(component, "visible"); // the component
        add(new JLabel(), "hidden"); // empty label
    public void showComponent() {, "visible"); 
    public void hideComponent() {, "hidden"); 
    public void setComponentVisible(boolean visible) {
        if (visible)
    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);
            b.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {