Search code examples
javaswingactionlistener

How do I execute a function in an ActionListener through the button which is clicked


This is the class I'm using

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SudokuFeld extends JFrame{
    private JPanel secondaryPanel;
    private JButton button1;
    private JButton button2;
    private JButton button3;
    private JButton button4;
    private JButton button5;
    private JButton button6;
    private JButton button7;
    private JButton button8;
    private JButton button9;
    private JButton[] bArr = new JButton[] {button1, button2, button3, button4, button5,button6, button7, button8, button9};
    ActionListener listener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
        }
    };


    public SudokuFeld() throws HeadlessException {
        int var = 0;
        for(JButton val : bArr ) {
            val.putClientProperty("number", var);
            val.addActionListener(listener);
            var++;
        }
    }



}

And what I want is to execute getClientProperty() in the ActionListener listener through the button which was clicked

I expected the number assigned to the button as output


Solution

  • Try

    ActionListener listener = new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        JButton jb = (JButton) e.getSource();
        Integer value = (Integer) jb.getClientProperty("number");
        ... // whatever else you need to do
      }
    };