Search code examples
javaswingjbuttonactionlistenerstack-overflow

Adding ActionListener in for cycle throws StackOverflowError


I am getting java.lang.StackOverflowError when I run this code:

Map<JButton, Integer> buttons = new HashMap<JButton, Integer>();
JPanel main = new JPanel(new GridLayout(4, 4, 4, 4));

    for(int i = 0; i < 16; i++) {
        JButton jb = new JButton(i+"");
        jb.addActionListener(new MyActionListener());
        switch(i) {
        case 0:
            jb.setText("1");
        case 1:
            jb.setText("2");
        case 2:
            jb.setText("3");
        (...) 
        case 15:
            jb.setText("/");
        }
        buttons.put(jb, i);
        main.add(jb);
    }

    this.getContentPane().add(main);

Why is that error happening? And how could I fix it? Thanks.


Solution

  • Ok I figured it out. The problem was with using external MyActionListener class. I had to create void actionPerformed() in class where I create new JButtons and also add there implements ActionListener.

    Anyway thanks for your answers.