0

When I run this following code, I get mutiple instances of my GUI application getting executed. I don't understand why this happen. Can anyone please explain me what is fishy going on here?

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class FirstApp {
    private MyActionListener mal = new MyActionListener();
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            FirstApp firstApp = new FirstApp();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public FirstApp () {
        initialize();
    }
    
    private void initialize() {
        JFrame f = new JFrame();//creating instance of JFrame  
        f.setSize(400,300);//400 width and 500 height  
        f.setLayout(null);//using no layout managers  
        f.setVisible(true);//making the frame visible  

        JButton b = new JButton("Click Me");//creating instance of JButton  
        b.setBounds(140,100,120, 40);//x axis, y axis, width, height  
        f.add(b);//adding button in JFrame  
        b.addActionListener(new FirstApp().mal);
    }
    
    private class MyActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            System.out.println("Hello!");
        }
    }
}

I think this has to do with the EventQueue.invokeLater() which is there by default when we create a new GUI App using WindowBuilder.

Shri
  • 109
  • 9
  • Yes, invokeLater() should be used. Don't remove code generated by your GUI builder. However, it is not the cause of your problem. – camickr May 22 '21 at 18:03
  • Perhaps it's best to know why you **should** use invokeLater. So check out [What does SwingUtilities.invokeLater() do?](https://stackoverflow.com/questions/6567870/what-does-swingutilities-invokelater-do) – WJS May 22 '21 at 18:09

1 Answers1

1

I get mutiple instances of my GUI application getting executed. I don't understand why this happen.

Because your code keeps creating multiple instances of your FirstApp class.

b.addActionListener(new FirstApp().mal);

So you create your class which attempts to add an ActionListener to the button, but instead creates a new instance of your app and the cycle repeats.

Just use:

b.addActionListener(new MyActionListener());

and get rid of your "mal" variable.

Also, don't use a null layout and setBounds(...). Swing was designed to be used with layout managers. Learn to use Swing properly.

Read the Swing tutorial on Layout Managers.

camickr
  • 321,443
  • 19
  • 166
  • 288