Skip to content
Advertisement

How to trigger another action listener after completion of ActionListener?

I created a GUI with a JFrame, JPanel, JLabel and a JButton.

 // JFrame
    Jframe f = new JFrame("");
 
 // JButton
    JButton b = new JButton("button1");

 // JLabel
    JLabel l = new JLabel("panel label");

 // JPanel
    JPanel p = new JPanel();

I added the button and the label to the panel. I added two ActionListeners for the button.

 b.addActionListener(e -> {
          //code
        });
 b.addActionListener(e -> {
          //code
        });

I want to execute the first action listener. Then execute the other one. Basically, I have some text that I want to output in the label, sequentially. I want for it to show “Hello” then “Goodbye” on the panel. The problem that it is giving me, is that it only shows the text from my second ActionListener “Goodbye”.

Advertisement

Answer

You can convert second one to the below sample. The reason it only show the second one because both runs immediately and you see the last one as label.

b.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed( ActionEvent e ) {
            
            Thread t = new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                        // set your label as Goodbye here
                        // add any other business logic
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                    
                }
                
            });
            t.start(); 
        }
        
    });
Advertisement