简体   繁体   English

向JButton数组添加侦听器;

[英]adding listeners to JButton array;

I have the following code which creates a JButton array on button click. 我有以下代码,它在单击按钮时创建一个JButton数组。 Ope[] is publically declared in class. Ope[]在类中公开声明。 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: 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);
        }
    }

}

JButton inherits "setName" Method from Component. JButton从Component继承“ setName”方法。 So if you set a name on the Button at initialization 因此,如果您在初始化时在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);

you can find wich button was pressed in the eventhandling 您会发现事件处理中按下了“ wich”按钮

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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