Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Components can be dynamically removed and added to a JFrame by using the following steps:

  1. Create an instance of the JFrame that you want to add or remove components from
  2. Call the remove() method on the JFrame instance and pass in the component that you want to remove
  3. Call the add() method on the JFrame instance and pass in the component that you want to add
  4. Call the revalidate() method on the JFrame instance to update the layout of the JFrame
  5. Call the repaint() method on the JFrame instance to repaint the window with the new components

Here is an example code snippet that demonstrates how to dynamically remove and add components to a JFrame:

import javax.swing.*;

public class ExampleFrame extends JFrame {

  public ExampleFrame() {
    setTitle("Example JFrame");
    setSize(300, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Add initial components
    JLabel label = new JLabel("Hello World");
    add(label);

    // Remove and add new component
    remove(label);
    JButton button = new JButton("Click me!");
    add(button);

    // Update layout
    revalidate();
    repaint();
  }

  public static void main(String[] args) {
    ExampleFrame frame = new ExampleFrame();
    frame.setVisible(true);
  }
}