Java detect pressed buttons

I have several panels in a JFrame window. Each time I will fill each panel differently. For example: I launched GUI: (image center panel, right panel, bottom panel). The central panel is filled with 20 buttons, the right panel with 10 buttons and the bottom panel with 3.

second launch of the GUI (the same gui). The central panel has 50 buttons, the right panel has 12 buttons, the bottom - 3.

Thus, each time a random number of buttons appear that cannot be unambiguously called. Given the fact that I do not have a unique name for each button (list only), I would like to know which buttons were pressed according to the panel to which they belong. is it possible?

0
source share
3 answers

Somehow buttons are created; Suppose you somehow number them as you can get 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 } } 
+3
source

ActionEvent has a getSource () method, which will be a link to the button that the button was clicked on. Then you can check the action of the command if you need to.

+1
source

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

+1
source

Source: https://habr.com/ru/post/1389187/


All Articles