Lerp
Lerp

Reputation: 3127

Java changing an existing component

I am trying to change a component from a JLabel to JComboBox when another option is added but for some reason the panel is not updating.

SSCCE:

public class SwitchComponent {
    public static void main(String[] args) { 
        JPanel panel = new JPanel();
        JComponent component = new JLabel("This is a test");

        panel.add(component);

        JComboBox<String> comboBox = new JComboBox<String>();
        comboBox.addItem("Testing..");
        comboBox.addItem("1.. 2.. 3..");

        component = comboBox;

        // I have tried with only one of the below lines and without any also...
        // Doesn't seem to have an effect.
        // I've also tried invoking the below methods on the panel instead.
        component.revalidate();
        component.repaint();

        JOptionPane.showConfirmDialog(null, panel, "Test",
                                      JOptionPane.OK_OPTION,
                                      JOptionPane.PLAIN_MESSAGE);
    }
}

Why is this happening? Shouldn't panel be referencing component such that any changes to component are reflected via panel?

Do I really have to completely reassemble the panel when the component changes?

Upvotes: 0

Views: 146

Answers (2)

camickr
camickr

Reputation: 324127

I.e. the label could be second in a series of three, I would want the combo box to remain second when the component is changed to the combo box. Hence why I was trying to change the reference

Use a Card Layout. It will replace a component at the same location.

Upvotes: 0

Mengjun
Mengjun

Reputation: 3197

When click YES/NO button on JOptionPane, JOptionPane will close.

We need to add the JComboBox to Panel again and use JOptionPane to show the Panel again in your code.

Have a try with this:

public class SwitchComponent {
public static void main(String[] args) { 
    JPanel panel = new JPanel();
    JComponent component = new JLabel("This is a test");

    panel.add(component);

    JOptionPane.showConfirmDialog(null, panel, "Test",
                                  JOptionPane.OK_OPTION,
                                  JOptionPane.PLAIN_MESSAGE);

    panel.remove(component);

    JComboBox<String> comboBox = new JComboBox<String>();
    comboBox.addItem("Testing..");
    comboBox.addItem("1.. 2.. 3..");
    panel.add(comboBox);

    // I have tried with only one of the below lines and without any also...
    // Doesn't seem to have an effect.
    // I've also tried invoking the below methods on the panel instead.
    panel.revalidate();
    panel.repaint();

    JOptionPane.showConfirmDialog(null, panel, "Test",
            JOptionPane.OK_OPTION,
            JOptionPane.PLAIN_MESSAGE);

}
}

Upvotes: 2

Related Questions