Java JButton数组ActionListener问题
我正在写一个程序,我遇到了一个问题 我创建了1个JLabel数组和1个JButton数组。 JLabel数组包含一个字符串,即俱乐部名称。 JButton数组包含一个只表示“Edit”的字符串 然后,For循环根据clubs数组的长度填充每个数组,并为每个按钮添加一个动作侦听器 当用户单击与JLabel对应的JButton时,它会启动一个事件。在本例中,我需要找出JLabel中存储的与JButton匹配的值 因为事件侦听器不知道它在循环中,所以我不能使用它 我如何实现我想要的目标 参见下面的代码Java JButton数组ActionListener问题,java,swing,jbutton,actionevent,Java,Swing,Jbutton,Actionevent,我正在写一个程序,我遇到了一个问题 我创建了1个JLabel数组和1个JButton数组。 JLabel数组包含一个字符串,即俱乐部名称。 JButton数组包含一个只表示“Edit”的字符串 然后,For循环根据clubs数组的长度填充每个数组,并为每个按钮添加一个动作侦听器 当用户单击与JLabel对应的JButton时,它会启动一个事件。在本例中,我需要找出JLabel中存储的与JButton匹配的值 因为事件侦听器不知道它在循环中,所以我不能使用它 我如何实现我想要的目标 参见下面的代码
JLabel clubs[] = new JLabel[99];
JButton editAClub[] = new JButton[99];
for(int i=0; i <= (allClubs.length - 1);i++)
{
clubs[i] = new JLabel("Club " + i);
editAClub[i] = new JButton("Edit");
editAClub[i].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
selectedClub = clubs[i].getText().toString();
System.out.println(selectedClub);
}
});
}
JLabel clubs[]=新JLabel[99];
JButton editAClub[]=新JButton[99];
对于(int i=0;i我将创建按钮和jlabel的映射,并在actionListener中传递操作源:
JLabel clubs[] = new JLabel[99];
JButton editAClub[] = new JButton[99];
//create a map to store the values
final HashMap<JButton,JLabel> labelMap = new HashMap<>(); //in JDK 1.7
for(int i=0; i <= (allClubs.length - 1); i++)
{
clubs[i] = new JLabel("Club " + i);
editAClub[i] = new JButton("Edit");
//add the pair to the map
labelMap.put(editAClub[i],clubs[i]);
editAClub[i].addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//get the label associated with this button from the map
selectedClub = labelMap.get(e.getSource()).getText(); // the toString() is redundant
System.out.println(selectedClub);
}
});
}
JLabel clubs[]=新JLabel[99];
JButton editAClub[]=新JButton[99];
//创建一个映射来存储值
final HashMap labelMap=new HashMap();//在JDK 1.7中
对于(int i=0;i)当前代码有什么问题?您不能在actionListener中使用i。Valek,这会引发NullPointerException的…我还必须使labelMap成为最终版本。尽管这两种方法都不起作用..问题解决了,我使用了Valek的想法…但是,我使用了e.getSource()而不是“this”.@RickyRodrigues修复。抱歉,我对匿名类声明中的这个
的不同级别感到困惑。如果它解决了您的问题,请随意接受。那么为什么不使用((JButton)e.getSource())?@MadProgrammer何必麻烦呢?get
将对象
作为其参数。