2

I have the following code which creates a JButton array on button click. Ope[] is publically declared in class. I have problem that I got null pointer. That is it doesn't print 2nd in loop ie. doesn't go in inner iteration. Please tell me how to handle the listeners for array. Thanks in advance.

for( int i=0,y=30; i<counter;i++,y+=15 )
{

        open[i]=new JButton( "Open" );
        open[i].setBounds( 380, y, 70, 15 );
        open[i].addActionListener( this );
        panelDisplay.add (open[i] );

        System.out.println(""+i);
}

The event handling in actionPerformed function is as follows:

for( int j=0; j<open.length; j++ )
{
    System.out.println("1st in a loop"+j);

    if( ae.getSource() != null )
    {
        if( ae.getSource() == open[j] )
        {
            System.out.println("2nd in a loop" +j);
            int id;
            String stringid;
            System.out.println("open of"+j+"is clicked");

            stringid = ""+table.getValueAt(j, 0);
            id = Integer.parseInt(stringid);
            fetchData(id);
            //ae.getSource().equals(null);
        }
    }

}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
vibhor
  • 59
  • 2
  • 7
  • Don't use `setBounds()`. Use a layout manager to layout the buttons. Post your SSCCE that demonstrates the problem. – camickr Apr 23 '13 at 15:38

1 Answers1

0

JButton inherits "setName" Method from Component. So if you set a name on the Button at initialization

        open[i]=new JButton( "Open" );
        open[i].setBounds( 380, y, 70, 15 );
        open[i].setName("Button"+i);
        open[i].addActionListener( this );
        panelDisplay.add (open[i] );

        System.out.println(""+i);

you can find wich button was pressed in the eventhandling

    int buttonNumber = Integer.parseInt(ae.getSource().getName().replace("Button",""))
    //... do eventhandling for Button["buttonNumber"]
mstrewe
  • 441
  • 3
  • 15
  • 1
    It will be better to use getName.equals("Button"+i) – bobby Apr 23 '13 at 15:24
  • -1, There is no need to us the setName() method for something like this. That is extra work that is not necessary. If this code works, then the original code should work. Although it is never recommended to use if/else or looping type logic to determine which object generated the event, if you do use this logic then you should check for the actual object, or maybe the "action command" of the object, not the name of the object. – camickr Apr 23 '13 at 15:35