I'd would know more about how e.getSource()
works in ActionListener
class,
My Code is Here :
public class ActionController implements ActionListener{
private MyButton theButton;
public void setTheButton(MyButton btn){
this.theButton = btn;
}
public void actionPerformed(ActionEvent e){
if(this.theButton == e.getSource()){
System.out.println(e.getSource().getName());
}
}
}
In my understanding, e.getSource()
will returns reference to the object that the event came from.
And now I don't understand why I can't call method of the source by doing like this :
System.out.println(e.getSource().getName());
I can only do By calling the private field theButton
in the CLass, like this:
System.out.println(this.theButton.getName());
while it is already this.theButton == e.getSource()
I can't understand why, can somebody explain more ?
Addition note, Why do I want to do this :
I can making a GUI with some action set to multiple button, And I want to separate the UI code and Action code in two class. My goal is let ActionController be the middle-man, calling function in another Class (Which those function able to reuse) while it has a list linking up button's name & the function.
I have read this question, The answer try to passing all the ui element while class is construct. Instead of that, I prefer to pass-in the ui element dynamicly by calling method after the class construct.
If it is able to call e.getSource().getName()
, it will be a lots clean to doing like :
private String[] element_funtion_table;
public void actionPerformed(ActionEvent e){
String eleName = e.getSource().getName();
String ftnName = this.getLinkedFtn(eleName);
if(!ftnName.equals("")){
this.callFtn(ftnName);
}
}
(a part of code, you got the idea) which it makes a lot easy to manage, because
while I can't e.getSource().getName()
I need to store array of MyButton, instead of just names of button.