简体   繁体   中英

adding listeners to JButton array;

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);
        }
    }

}

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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM