我有以下代码,它在单击按钮时创建一个 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);
}
}
}
最佳答案
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"]
关于java - 将监听器添加到 JButton 数组;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16172878/