Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8891519
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T22:46:02+00:00 2026-06-14T22:46:02+00:00

A question similar to this has been asked several times. See e.g. here and

  • 0

A question similar to this has been asked several times. See e.g. here and here.

Yet I would really like to understand why it is that my code doesn’t work. As has been answered in other versions of this question, a CardLayout would probably suffice, though in my case I’m not sure if it’s ideal. In any case, what I’m interested in is understanding conceptually why this doesn’t work.

I have a JFrame who’s content pane listens to key events. When a key is pressed in the content pane, the content pane tells the JFrame to update itself with a new content pane. Here’s a simple example of the problem:

This code is fully compilable. You can copy-paste it and run it as is.

Here’s my JFrame:

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class SimpleSim extends JFrame{

    private static SimpleSim instance = null;

    public static SimpleSim getInstance(){
        if(instance == null){
            instance = new SimpleSim();
        }

        return instance;
    }

    private SimpleSim(){}

    public void initialize(){

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setExtendedState(Frame.MAXIMIZED_BOTH);
        this.pack();
        this.setVisible(true);

        update();
    }

    public void update(){
        System.out.println("SIMPLE_SIM UPDATE THREAD: " + Thread.currentThread().getName());
        Random rand = new Random();

        float r = rand.nextFloat();
        float g = rand.nextFloat();
        float b = rand.nextFloat();

        SimplePanel simplePanel = new SimplePanel(new Color(r, g, b));
        JPanel contentPane = (JPanel) this.getContentPane();

        contentPane.removeAll();
        contentPane.add(simplePanel);
        contentPane.revalidate();
        contentPane.repaint();

        validate();
        repaint();

    }


}

And here’s my JPanel that serves as my content pane:

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;


public class SimplePanel extends JPanel implements KeyListener {

    public SimplePanel(Color c){

        setFocusable(true);
        setLayout(null);
        setBackground(c);
        setVisible(true);
        this.addKeyListener(this);
    }
    public void keyTyped(KeyEvent keyEvent) {
        if(keyEvent.getKeyChar() == 'a'){
            System.out.println("a");
            System.out.println("SIMPLE_PANEL KEY PRESS THREAD: "  + Thread.currentThread().getName());
            SimpleSim.getInstance().update();
        }
    }

    public void keyPressed(KeyEvent keyEvent) {
    }
    public void keyReleased(KeyEvent keyEvent) {
    }
}

Oddly, it works the first time you press a, but not after. My guess is that there is a threading issue going on here. I can see that when update is first called it’s called on the main thread. The next time it’s called on the EDT. I’ve tried calling update() using invokeLater() and that also didn’t work. I’ve found a workaround using a different design pattern, but I’d really like to understand why this doesn’t work.

Also, simple class to run:

public class Run {

    public static void main(String[] args){
        SimpleSim.getInstance().initialize();
    }
}

Note: The seemingly redundant call to validate and repaint the JFrame was done to try to appease the advice posted on the second link I provided, which stated that:
Call validate() on the highest affected component. This is probably the muddiest bit of Java’s rendering cycle. The call to invalidate marks the component and all of its ancestors as needing layout. The call to validate performs the layout of the component and all of its descendants. One works “up” and the other works “down”. You need to call validate on the highest component in the tree that will be affected by your change.
I thought this would cause it to work, but to no avail.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T22:46:03+00:00Added an answer on June 14, 2026 at 10:46 pm

    I made some modifications to your code, sorry, but it made testing SOooo much easier…

    The import change that I can see is in the update method. Basically I simply called revalidate on the frame

    Revalidate states

    Revalidates the component hierarchy up to the nearest validate root.

    This method first invalidates the component hierarchy starting from
    this component up to the nearest validate root. Afterwards, the
    component hierarchy is validated starting from the nearest validate
    root.

    This is a convenience method supposed to help application developers
    avoid looking for validate roots manually. Basically, it’s equivalent
    to first calling the invalidate() method on this component, and then
    calling the validate() method on the nearest validate root.

    I think that last part is what you were missing in you own code.

    public class SimpleSim extends JFrame {
    
        private static SimpleSim instance = null;
    
        public static SimpleSim getInstance() {
            if (instance == null) {
                instance = new SimpleSim();
            }
    
            return instance;
        }
    
        private SimpleSim() {
        }
    
        public void initialize() {
    
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setSize(400, 400);
            this.setVisible(true);
            setLayout(new BorderLayout());
    
            update();
    
        }
    
        public void update() {
            System.out.println("NEXT: " + Thread.currentThread().getName());
            Random rand = new Random();
    
            float r = rand.nextFloat();
            float g = rand.nextFloat();
            float b = rand.nextFloat();
    
            SimplePanel simplePanel = new SimplePanel(new Color(r, g, b));
            JPanel contentPane = (JPanel) this.getContentPane();
    
            getContentPane().removeAll();
            add(simplePanel);
    
            revalidate();
        }
    
        public class SimplePanel extends JPanel {
    
            public SimplePanel(Color c) {
    
                setFocusable(true);
                setLayout(null);
                setBackground(c);
                setVisible(true);
                requestFocusInWindow();
                InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
                ActionMap am = getActionMap();
    
                im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "A");
                am.put("A", new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("a");
                        System.out.println("KEY: " + Thread.currentThread().getName());
                        SimpleSim.getInstance().update();
                    }
                });
    
            }
        }
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    SimpleSim.getInstance().initialize();
                }
            });
        }
    }
    

    Also, I’d suggest you take advantage of the key bindings API instead of using KeyListener. It will solve some of the focus issues 😉

    UPDATE

    After some time testing various permutations, we’ve come to the conclusion that the major issue is related to a focus problem.

    While the SimplePanel was focusable, nothing was giving it focus, meaning that the key listener fails to be triggered.

    Added simplePanel.requestFocusInWindow AFTER it was added to the frame seems to have allowed the key listener to remain active.

    From my own testing, with out a call to revalidate the panels did not update.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is a variation on a question that has been asked here several times.
I know this question has been asked several times and I read those with
This question has been asked, in one form or another, a dozen times here,
I know this question has been asked several times, but I can't quite seem
I can see this question (or a similar one) has been asked a few
I know this very similar question has been asked before quite a few times
I know this question has been asked many times and here I am again.
Something similar to this question has been asked here - HTML/CSS Gradient that stops
I know this question has been asked many times here and elsewhere before as
I realize that this question has been asked many times, but I've yet to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.