简体   繁体   中英

ActionListener on array of JButtons

I've created a an array of JButtons that have a random color assigned to them when created as opposed to manually creating each button and assigning random colors to them. I'm now at a point where I want to use change the color, at random, of whichever button is clicked. I'd like to do it the same way as I've created and added the buttons so far(through the use of loops).

Though doing it the way I thought would work has failed. I'm given "local variable is accessed from within inner class; needs to be declared final" . I'm that if I use final it can't be changed and now I'm at a loss.

Is there a possible workaround?

package test;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.EventHandler;
import java.lang.String;
import java.util.Random;

public class TEST

{

/**
 * @param args the command line arguments
 */
public static Random rand = new Random();
public static int oh;

public void btnPress(ActionEvent e, JButton[] jButts, float r, float g, float b) {
    for (int y = 0; y < jButts.length; y++) {
        if (e.getSource() == jButts[y]) {
            jButts[y].setBackground(Color.getHSBColor(r, g, b));
        }
    }
}

public static void main(String[] args) {
    JFrame frame = new JFrame("Suhp, Brah?");
    frame.setLayout(new BorderLayout());
    frame.setVisible(true);
    frame.setBackground(Color.magenta);
    frame.setSize(400, 400);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new GridLayout(4, 4));
    String[] numbs = {"0", "1", "2", "3", "4", "5", "6", "7"};
    final JButton[] jButts = new JButton[numbs.length];//0-7

    for (int i = 0; i < 8; i++) {

        jButts[i] = new JButton(numbs[i].toString());
        //String leString = rand.nextInt(255).toString;
        jButts[i].setBackground(Color.getHSBColor(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
    }
    for (int x = 0; x < 8; x++) {
        frame.add(jButts[x]);
    }
    //ActionListener
    for (int i =0; i < 8; i++) {

        jButts[i].addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                i++;
                jButts[i].setBackground(Color.getHSBColor(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
            }
        });
    }

}
}

There's no need to use i in the ActionListener . You can get the button using ActionEvent#getSource :

jButts[i].addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        JButton button = (JButton) e.getSource();
        button.setBackground(Color.getHSBColor(rand.nextFloat(),
                rand.nextFloat(), rand.nextFloat()));
    }
});

here's a workaround,

//ActionListener
for (int i =0; i < 8; i++) 
{
    final int temp = i; // assign to temporary variable
    jButts[temp].addActionListener(new ActionListener() 
    {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            // i++; Not sure what you're trying to do here..
            jButts[temp].setBackground(Color.getHSBColor(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
        }
    });
}

but I highly recommend rethinking your approach.

// ActionListener
    ActionListener listener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JButton button = (JButton) e.getSource();
            button.setBackground(Color.getHSBColor(rand.nextFloat(),
                    rand.nextFloat(), rand.nextFloat()));
        }
    };

    for (int i = 0; i < 8; i++)
        jButts[i].addActionListener(listener);

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