Serpace
Serpace

Reputation: 83

Changing a label during ActionEvent

I am trying to enable/disable a label when a button is pressed and i want to do this during the event and not after it. As you can see below, i try to enable/disable the two labels: lblKeyboard and lblGamepad.

They end up running after the "RemoteControl.run();" is executed but i want it to happen before that. Any way i can do that?

Thank you!

JButton btnGamepad = new JButton("Gamepad");
        btnGamepad.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                    if(cont_state == 0){
                        if(RemoteControl.findGamePad() == true){
                            cont_state = 1;
                            game_status = "on";
                        }
                        else{
                            game_status = "off";
                            key_status = "on";
                            JOptionPane.showMessageDialog(null, "Controller not found!");
                            cont_state = 0;
                        }
                    }

                    if(cont_state == 1){    

                        System.out.println("CONNECTED GAMEPAD!");
                        lblKeyboard.disable();
                        lblGamepad.enable();
                        frame.repaint();
                        RemoteControl.run();

                        cont_state = 0;
                    }

            }
        });

Upvotes: 0

Views: 50

Answers (2)

Renatols
Renatols

Reputation: 388

ActionEvents are run on the EDT which is also responsible for painting. Once you change the labels state, Swing issues a request for repaiting the Label. The thing is that this request is posted on a queue and will be executed once the EDT is free and, as you can see, the EDT is busy running your code so no repainting for you! Depending on the nature of your code, you should consider using a SwingWorker or simply moving RemoteControl.run() to another Thread as in

new Thread(new Runnable() {
     @override
     public void run() {
          RemoteControl.run();
     }
}).start();

Upvotes: 1

camickr
camickr

Reputation: 324128

Code in an event listener executes on the Event Dispatch Thread (EDT) and the GUI can't repaint itself until all the code has finished executing. Read the section from the Swing tutorial on Concurrency for more information on the EDT.

Try wrapping your RemoteControl.run() code in a SwingUtilities.invokeLater(...). This will place the code at the end of the EDT, which might give Swing a changes to repaint the state of the two labels.

SwingUtilities.invokeLater(new Runnable()
{
    public void run()
    {
        RemoteControl.run()
    }
});

This assumes your code updates the GUI. If not, then just use a separate Thread.

Upvotes: 1

Related Questions