2

我有以下代码在按钮单击时创建一个 JButton 数组。Ope[]在课堂上公开声明。我有空指针的问题。那就是它不会在循环中打印第二个,即。不进行内部迭代。请告诉我如何处理数组的侦听器。提前致谢。

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

actionPerformed 函数中的事件处理如下:

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

}
4

1 回答 1

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"]
于 2013-04-23T15:20:42.573 回答