Homeroe
Homeroe

Reputation: 105

Adding attributes to jButton [JAVA]

Lets say i have an array of 100 employees. Each employee in the array, is an instance of the class Employee, that have many attributes, such as name, direction, salary, etc.

I want to display, 1 button for each employee in the array, and when you click one, you get the information of that employee.

What i don't know, is how can i link a button to an specific employee. I Was thinking on, somehow, attaching an Integer variable to the button, so i know which employee is related to that specific button, but, i don't really know how to do that.

Anyone cares to give me some advice on this?

Upvotes: 3

Views: 2407

Answers (3)

eugcomax
eugcomax

Reputation: 189

If you get "this" inside listener you get a reference to listener's object. You should use getSource() method, like:

JButton j = new JButton("click here");
    j.putClientProperty("id", "employee1");

    j.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {

            JButton source = (JButton)ae.getSource();
            String id = (String) source.getClientProperty("id");
            System.out.print(id);
        }
    });

Will print - employee1.

Upvotes: 1

Pieter De Bie
Pieter De Bie

Reputation: 1212

You can use the putClientProperty and getClientProperty to attach any object to a JComponent.

Upvotes: 1

eugcomax
eugcomax

Reputation: 189

You could use setName(employeeId) method for JButton to set Employee's id or use putClientProperty("id", employeeId), when you get a callback at button's listener you could get the name or your property.

Upvotes: 1

Related Questions