user253530
user253530

Reputation: 2591

java detect clicked buttons

I have multiple panels on a JFrame window. I am going to populate each panel differently every time. For example: i start the GUI: (image center panel, right panel, bottom panel). Center panel is populated with 20 buttons, right panel with 10 buttons and bottom panel with 3.

second start of the GUI (same gui). Center panel has 50 buttons, right panel has 12 buttons, bottom has 3.

So everytime there is a random number of buttons, impossible to be all uniquely named. Given the fact that I don't have a unique name for each button (just a list) I would like to know which buttons were clicked according to the panel they belong to. is that possible?

Upvotes: 0

Views: 12828

Answers (3)

I82Much
I82Much

Reputation: 27326

Somehow the buttons are being created; Let's assume you are somehow numbering them in a way you can retrieve later.

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.List;
import java.util.ArrayList;
import javax.swing.JButton;


public class ButtonTest extends JFrame implements ActionListener {

    public ButtonTest() {
        super();
        initGUI();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    private final List<JButton> buttons = new ArrayList<JButton>();
    private static final int NUM_BUTTONS = 20;

    public void initGUI() {
        JPanel panel = new JPanel();
       for (int i = 0; i < NUM_BUTTONS; i++) {
           String label = "Button " + i;
           JButton button = new JButton(label);
           button.setActionCommand(label);
           button.addActionListener(this);
           buttons.add(button);
           panel.add(button);
       }
       getContentPane().add(panel);
    }

    public static void main(String[] args) {
        new ButtonTest();
    }

    public void actionPerformed(ActionEvent e) {
        String actionCommand = ((JButton) e.getSource()).getActionCommand();
        System.out.println("Action command for pressed button: " + actionCommand);
        // Use the action command to determine which button was pressed
    }


}

Upvotes: 4

Etaoin
Etaoin

Reputation: 8724

If you want to know which panel contains the button, try calling getParent() on the JButton itself. To find out which button was clicked, as camickr suggests, use getSource() on the ActionEvent.

Upvotes: 1

camickr
camickr

Reputation: 324108

The ActionEvent has a getSource() method which will be the reference to the button that was clicked. You can then check the action command of the button if you need to.

Upvotes: 1

Related Questions