Question

In a for loop, I want to

  • initialize JButtons [] bts .
  • add the buttons to a panel pan3 .
  • add an ActionListener to each JButton .

here what I've got so far :

for(int i = 0 ;i < bts1.length ; i++){
        bts1[i] = new JButton(""+i);
        pan3.add(bts1[i]);
        //The NullPointerException happens after this line . 
        bts[i].addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae){
                int j = 0 ;
                screen.setText(screen.getText()+bts[j].getText());
                j++;
            }
        });
    }

My question is how to solve the NullPointerException ? note for the j I add it because when I tried to use the i , a compiler error occurs ,

Was it helpful?

Solution

You initialized JButton as bts1 and calling it as bts. I think that caused the error.
Also,

Declare int i=0; as global scope and for(i = 0 ;i < bts1.length ; i++) then you can use i instead of j.
Or else use as following:

for(int i = 0 ;i < bts1.length ; i++){
        bts1[i] = new JButton(""+i);
        pan3.add(bts1[i]);
        final int j=i; 
        bts1[i].addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae){                   
                screen.setText(screen.getText()+bts1[j].getText());
            }
        });
    }

OTHER TIPS

You are using two different arrays of JButtons, bts and bts1.

  • In your loop you are creating a JButton and assign it to bts1[i].
  • In the ActionListener part you are accessing bts[j].

Have you initialized also bts[j] somewhere? If not you will run into a NPE.

Try the event source instead

screen.setText(screen.getText()+((JButton)ae.getSource()).getText());
try this:
for(int i = 0 ;i < bts1.length-1 ; i++){
   //rest of your code
}

As the array of 10 elements has elements with indexes 0 through 9, not 0 through 10.

Beforr you add the button to Panels. You need add Listener for button first.

Have a try with the following code first.

    //The NullPointerException happens after this line . 
    bts[i].addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae){
            int j = 0 ;
            screen.setText(screen.getText()+bts[j].getText());
            j++;
        }
    });

    **pan3.add(bts1[i]);**
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top