简体   繁体   中英

actionListener on a JButton created from vector

I've been searching the web for an answer to my specific basic problem, but was unable to find one. I must say I am new to programming and I have to do this for school. I have created an interface of a 6/49 lottery, where you have to click 6 JButtons, creating your "lucky" numbers. In my interface .java, I've created my buttons this way:

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

Note: "choixNumero" is a gridLayout ( 7 x 7 )

In another .java , I'm creating an actionListener to my JButton b, but that doesn't seems to work. Here is how I wrote it:

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

and heres the code of my EcouteurCombinaison:

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éros\n Cliquer sur Soumettre pour valider", "Information", JOptionPane.INFORMATION_MESSAGE);   
        }    
    }
}

So basically, I'm trying to add the index or the value of my JButton to the vector everytime a button is pushed. I will then send it to another .java

I've implemented others actionListener to my code and they work fine ( JButton, RadioButton, JComboBox ). I don't understand why nothing happens when I click my buttons.

I tried to make this as clear as possible, without pasting all the code.

Edit: The ActionListener works with the last button only ( 49 ). How can I make it listen to all b Buttons ?

You are continually reassigning the value of b in that loop. When the loop completes, the last JButton to be created is assigned to it. You then bind an ActionListener to that button, but none of the others. I'm not sure why you expected a single invocation of intProjet.b.addActionListener() to add it to all JButtons.

intProjet.b refers to the last button created in your loop, so the result is expected. Instead, you can give each button its own instance of a listener, as shown here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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