I've 2 Objects I'm concerned with at the moment: a controller and a class creating an event.
I've got it all working with an ActionListener variable in the source class, set by an anonymous ActionListener object and method from the controller.
But I need access to data from the source class back in the controller. I'm capable of extending EventListener and using a custom EventObject, but that seems a bit overkill for one bit of data.
Is there an easy way to just extend ActionEvent and create an extra variable that I can access in the Listener's actionPerformed() method? ActionEvent's constructor is just confusing me.
public class NotesEvent extends ActionEvent{
public NotesEvent(Object source, int id, String command){
super(source, id, command);
}
}
I don't know what to pass for the 'identifier' when instantiating the event.
Maybe I've missed something simple - I've only ever really learned to do this the long way round with custom classes.
Any help would be appreciated
I was making the mistake of not downcasting the custom event in the controller, so I thought that ActionListener wouldn't play nice with a custom event - but it does seem to (which is what I initially thought)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class Target {
ActionListener listener;
int data = 1;
public Target(){
JButton b = new JButton("Press Me");
b.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
CustomEvent ce = new CustomEvent(data, Target.this, 0, "Command");
if(listener != null) listener.actionPerformed(ce);
}
});
}
public void setListener(ActionListener listener){
listener = listener;
}
}
class CustomEvent extends ActionEvent{
int data;
CustomEvent(int data, Object source, int id, String command){
super(source, id, command);
this.data = data;
}
public int getData(){
return data;
}
}
The controller class:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class Controller {
Target t = new Target();
public static void main(String[] args){
Controller c = new Controller();
}
public Controller(){
t.setListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
//here was my problem
System.out.println(((CustomEvent)e).getID());
}
});
}
}
I'm still not entirely sure about the data I should be passing to the ActionEvent constructor though.
Hope the above makes clear what I was trying to achieve (I know it's not actually complete in terms of the UI appearing.)
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.