I have a button that adds to a panel that adds to a frame. Now when I click this button I want it to call the method eat() which is a method of the Lion class. Now how would I do this with out containing the new object within the mousePressed method the below creates a new instance of the object each time it's clicked. I only want one instance of the object and to call the method on that instance how do I do this?
btnOpenNewFile.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
Lion adam = new Lion("Adam");
Cat meo = new Cat("Meo");
adam.eat(meo);
}
});
Define the object as member attribute of the class:
final Lion adam = new Lion("Adam");
public void clickMe(){
btnOpenNewFile.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
Cat meo = new Cat("Meo");
adam.eat(meo);
}
});
}
Create it outside and use it in the Listener but you will have to make it final
. You may initialize it in the constructor though!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.