I want something like this:
public abstract class ListenerEx<LISTENER, PARENT> implements LISTENER {
PARENT parent;
public ListenerEx(PARENT p) {
parent = p;
}
}
But it doesn't compile. Is there a better solution?
Is there something in Java like C++ template that would do check syntax after template deduction?
The following explains why I need such a ListenerEX class,
if you already know what it is, you don't need to read the following.
I have a main window, and a button on it, and I want to get access to some method of the main window's within the listener:
public class MainWindow extends JFrame {
public void doSomething() {
/* ... */
}
public void doSomethingElse() {
/* ... */
}
private JButton button;
public MainWindow() {
button = new JButton(...);
add(button);
button.setActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doSomething();
doSomethingElse();
}
});
}
}
This would compile but does not work properly all the time.
(Why would it compile when the ActionListener does not have doSomething() method?)
Of course we can do it like this:
public class MainWindow extends JFrame {
public void doSomething() {
}
public void doSomethingElse() {
}
private JButton button;
public MainWindow() {
button = new JButton(...);
add(button);
class ActionListener1 implements ActionListener {
MainWindow parent;
public ActionListener(MainWindow p) {
parent = p;
}
public void actionPerformed(ActionEvent e) {
parent.doSomething();
parent.doSomethingElse();
}
}
button.setActionListener(new ActionListener1(this));
}
}
However I hate this style ...
So I tried:
public abstract class ActionListenerEx<P> implements ActionListener {
P parent;
public ActionListenerEx(P p) {
parent = p;
}
}
public class MainWindow extends JFrame {
public void doSomething() {
}
public void doSomethingElse() {
}
private JButton button;
public MainWindow() {
button = new JButton(...);
add(button);
button.setActionListener(new ActionListenerEx<MainWindow>(this) {
public void actionPerformed(ActionEvent e) {
parent.doSomething();
parent.doSomethingElse();
}
});
}
}
But there's lots of Listeners beside the ActionListener ...
public abstract class ActionListenerEx<LISTENER, PARENT> implements LISTENER {
PARENT parent;
public ActionListenerEx(PARENT p) {
parent = p;
}
}
However, it won't compile ...
I am fresh at Java, and I wonder if there's already better solution.