Search code examples
javaswingjpaneljoptionpane

Problem: The use of JOptionPane stops my JPanels from switching


So the purpose of this code is to use JOptionPane to get a user input, verify it, make sure the input is "Hello World", and if it is, switch from the red JPanel to the blank one with the JLabel Hello World at the top. However, when "Hello World" is typed into the textfield in the JPanel and OK is clicked, the red JPanel is removed but the blank one with the JLabel does not appear. I used the isDisplayable() method to check if the blank JPanel with the JLabel is displayed and the result is true. I am not sure what the issue is or how to solve it. This is my code:

import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.lang.*;
import javax.sound.sampled.Line;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.*;

import static javax.swing.WindowConstants.EXIT_ON_CLOSE;

public class Main {

    private static JFrame frame = new JFrame();
    private static JPanel colorPanel = new JPanel();
    private static JPanel testPanel = new JPanel();
    private static JLabel testLabel = new JLabel("Hello World");

    public static void main(String[] args) {
        
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setResizable(false);
        colorPanel.setBackground(Color.RED);
        frame.add(colorPanel);

        frame.setVisible(true);
        String input = JOptionPane.showInputDialog("Enter");
        if(input.equals("Hello World"))
        {
            frame.remove(colorPanel);
            frame.validate();
            frame.repaint();
            testPanel.add(testLabel);
            frame.add(testPanel);
        }

    }
}

Solution

  • frame.validate() should be frame.revalidate() and should happen after all components adds/removes"

    if(input.equals("Hello World"))
    {
        frame.remove(colorPanel);
        testPanel.add(testLabel);
        frame.add(testPanel);
        frame.revalidate();
    }