NotCamelCase
NotCamelCase

Reputation: 1083

Adding button handlers in loop

I have a few JButtons and am trying to add their action listeners in for loop but it gives null pointer exception, however no problem occurs if i add them one by one. I'm wondering what my wrong point is. Thanks.

JButton[ ] myButtonArray = { but1, but2, but3 };
ButtonHandler bh = new ButtonHandler();

for (JButton cur : myButtonArray) {    // I tried standard for loop as well.
    cur.addActionListener(bh);
}

Upvotes: 0

Views: 515

Answers (3)

bragboy
bragboy

Reputation: 35562

Works perfectly fine for me.. Try this demo

enter image description here

package sof;

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

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

public class CustomLayoutFrame{
    public static void main(String args[]) {
        JFrame frame = new JFrame("Custom Layout Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setLayout(new GridLayout(3,1));

        JButton but1 = new JButton("Button1");
        JButton but2 = new JButton("Button2");
        JButton but3 = new JButton("Button3");

        JButton[ ] myButtonArray = { but1, but2, but3 };
        ButtonHandler bh = new ButtonHandler();

        for (JButton cur : myButtonArray) {    // I tried standard for loop as well.
            cur.addActionListener(bh);
        }

        frame.add(but1);
        frame.add(but2);
        frame.add(but3);

        frame.setSize(300, 150);
        frame.setVisible(true);
      }
}

class ButtonHandler implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent arg0) {
        System.out.println(((JButton)(arg0.getSource())).getText() + " Clicked !");

    }
}

Upvotes: 5

vextorspace
vextorspace

Reputation: 934

I would guess at least one of your buttons is null - ie but1, but2, or but3 (or all of them) were not initialized. Wh

Upvotes: 1

Tedil
Tedil

Reputation: 1933

And you did initialize but1, but2 and but3? Because that's the most probable source of your nullpointerexception.

Upvotes: 1

Related Questions