Search code examples
javajframelabeljlabel

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;
                    }

            }
        });

Solution

  • 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();