user2130057
user2130057

Reputation: 406

Recognizing components in swing?

I want to keep track of my components by which order they were added. So the first component added is 1, second is 2, etc. When a component is selected and changed, I want to be able to recognize which of these components I'm working with. For example, I add two components to the frame. Then, I go back and change the first component. I'd like to be able to somehow know which component I'm working with.

To give some context, it's just a window right now where you can add, drag, and edit text. I want to keep track of the components in the frame, because I'm sending that information to another class and updating dynamically.

If this isn't clear, I will try to explain further. Does anyone know how to achieve what I'm trying to do?

Upvotes: 1

Views: 64

Answers (1)

Bill K
Bill K

Reputation: 62769

You can keep instance variables of each of your important components, when you get an event from a component you compare it to that instance variable.

This can also be done by adding them to a map. This way you can store meta data (before the event):

map.put(button, "My Button");

then in the event retrieve it:

String name=map.get(e.getSource());
assertEquals("My Button", name);

The really nice thing is that the thing you are associating the button with doesn't have to be a string, it can be any object. So if you want to execute the "run" method on some arbitrary runnable when any button is clicked, you only need a single event handler for all your buttons (or all your controls) with one line like this:

map.get(e.getSource()).run();

short and sweet.

Upvotes: 2

Related Questions