0

I'm using IntelliJ and I have a form full of components placed inside several JPanel containers. I would like to change only a single component of a single panel when the button is pressed. I tried to remove all the components of that panel and add what I need but no results.

To be precise I would like a JLabel to become a JTextField.

How can I do this without drawing the GUI again and only changing that component?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    Use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). Add the label and text field to a panel with card layout. Add that panel to the GUI. – Andrew Thompson Oct 23 '20 at 11:40
  • BTW - please actually *read* the description of tags before adding them to a question. The [tag:replace] relates to strings, not components. – Andrew Thompson Oct 23 '20 at 11:43
  • 1
    @AndrewThompson Thank you! I'm sorry for the extra-tag, I will read the descriptions next time! – Brawchello Oct 23 '20 at 11:45

1 Answers1

-1

You should use the jframe.remove(Component comp) method and than use the jframe.add(Component comp).finally, don't forget the jframe.revalidate() method to update your JFrame. for example:

JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel l = new JLabel("hello");
        f.add(l);
        f.pack();
        f.setVisible(true);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JTextField tf = new JTextField();
        f.remove(l);
        f.add(tf);
        f.revalidate();

After 3 seconds, the JLabel in the JFrame will replaced by a JTextField.

Programmer
  • 803
  • 1
  • 6
  • 13
  • (1-) The requirement states: *I have a form full of components...* - yes removing the component is easy, but how do you know where to insert the component back into the panel? This is why the `CardLayout` should be used. – camickr Oct 25 '20 at 15:15