开发者

java detect clicked buttons

开发者 https://www.devze.com 2022-12-31 17:49 出处:网络
I have multiple panels on a JFrame window. I am going to populate each panel differently every time. For example:

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 (j开发者_高级运维ust a list) I would like to know which buttons were clicked according to the panel they belong to. is that possible?


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
    }


}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号