Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top