从vector创建的JButton上的actionListener



我一直在网上搜索我的特定基本问题的答案,但找不到。我必须说我是编程新手,我必须为学校做这件事。我创建了一个6/49彩票的界面,在那里你必须点击6个J按钮,创建你的"幸运"数字。在我的interface.java中,我以这种方式创建了按钮:

JButton b;
for (i = 1; i <= 49; i ++)
{           
String  s = String.valueOf(i);
b = new JButton(s); 
if (i % 2 == 0)            
b.setForeground(new Color(3, 121, 184));
else
b.setForeground(new Color(228, 44, 44));            
choixNumero.add(b);  

注:"choixNumero"是一个网格布局(7 x 7)

在另一个.java中,我正在为JButton b创建一个actionListener,但这似乎不起作用。以下是我的写作方式:

intProjet.b.addActionListener(new EcouteurCombinaison()); // where "intProjet" is my interface.java

这是我的生态组合的代码:

private int []  nums;
private int    nbRestant = 6;
private class EcouteurCombinaison implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
if (nbRestant > 0)
{
//nums[nbRestant] = indexOf(e)); //will have to find a way to get index of the button pressed
nbRestant --;
intProjet.valNbRestant.setText("" + nbRestant);
}
else
{
JOptionPane.showMessageDialog(null, "Vous avez choisis vos 6 numérosn Cliquer sur Soumettre pour valider", "Information", JOptionPane.INFORMATION_MESSAGE);   
}    
}
}

所以基本上,每次按下按钮时,我都会尝试将JButton的索引或值添加到向量中。然后我会把它发送到另一个.java

我已经在代码中实现了其他actionListener,它们运行良好(JButton、RadioButton、JComboBox)。我不明白为什么当我点击按钮时什么都没发生。

我试图在不粘贴所有代码的情况下尽可能清楚地说明这一点。

编辑:ActionListener只能使用最后一个按钮(49)。如何让它收听所有b按钮?

intProjet.b指的是在循环中创建的最后一个按钮,因此结果是意料之中的。相反,您可以为每个按钮提供自己的侦听器实例,如下所示。

您在该循环中不断重新分配b的值。当循环完成时,将最后一个要创建的JButton分配给它。然后将ActionListener绑定到该按钮,但不绑定其他按钮。我不知道您为什么期望通过一次intProjet.b.addActionListener()调用将其添加到所有JButton中。

最新更新