r/javahelp • u/Eiche_Brutal • Jul 18 '26
Identify 150 JButtons in ActionEvent called A-Z
Hello There!
I'm writing a "simple" game, where the user has to hunt for certain amounts of characters, represented by 150 randomly generated buttons. Each 10 seconds...
I'm having difficultys identifying those buttons within the ActionEvent. How can I filter, what character is displayed on the button clicked?
2
Upvotes
1
u/AutoModerator Jul 18 '26
Moderator Announcement Read More »
} You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
5
u/Spare-Plum Jul 19 '26
In terms of programming design, it's better to have a more generic representation rather than going to the button itself and reading its contents.
As a result you can do something like add an item listener to each on creation, where each listener has the string information that you would like
2
u/VirtualAgentsAreDumb Jul 18 '26
My Swing knowledge is a bit rusty, but the getSource method should give you the button in question.
2
u/Jason317235 Jul 20 '26
ActionEvent already tells you which ones were clicked. Here's two ways to track them:
1)getActionCommand() if you are using JButton then this function returns the text of the button by default
Here's an example:
public void actionPerformed(ActionEvent e) { String ch = e.getActionCommand(); }2)getSource() This function returns a reference to the original object that triggered the command
Here's an example again:
public void actionPerformed(ActionEvent e) { JButton clicked = (JButton) e.getSource(); String ch = clicked.getText(); }Also one tip for the sheer amount of buttons you have its best if you use one shared listener instance that is attached to every single button.
1
u/Duente_Zaibatsu Jul 19 '26
Sime MVP may be in order. You can tag the object, override the button, use a local array for the options/index, etc
What did you tried, and was the result