首页 文章

将监听器添加到JButton数组;

提问于
浏览
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);
        }
    }

}

1 回答

  • 0

    JButton从Component继承“setName”方法 . 因此,如果您在初始化时在Button上设置名称

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

    你可以在事件处理中找到按下按钮的方法

    int buttonNumber = Integer.parseInt(ae.getSource().getName().replace("Button",""))
        //... do eventhandling for Button["buttonNumber"]
    

相关问题