user1306777
user1306777

Reputation: 489

JButton adding properties

Is there a way to get the propery value we declared this way?

JButton button = new javax.swing.JButton(){
    public int value=0;
}

button.addActionListener(listener);
//in action listener
public void ActionPerformed(ActionEvent evt){

JButton btn = (JButton)evt.getSource();
btn.value =2; //error
}

Upvotes: 2

Views: 3261

Answers (2)

MByD
MByD

Reputation: 137362

You cannot access properties / methods of annonymous class outside of the instance itself.

The reason is that the compiler knows that btn is a JButton, not your extension, and you can't cast to this extension, as it doesn't have a name.

You need to create an internal class or class in a separate file and instantiate it, for example:

static class MyButton extends JButton {
    public int value=0;
}

// ....
MyButton btn = new MyButton();
btn.addActionListener(listener);
// ....

@Override public void actionPerformed(ActionEvent evt){
    MyButton btn = (MyButton)evt.getSource();
    btn.value = 2; 
}

Upvotes: 4

ControlAltDel
ControlAltDel

Reputation: 35051

What you can do is use Component.setName() to save at least a string with your Component.

Upvotes: 0

Related Questions