Tim said:
Hi
My base class has buttons who's events I want to handle in the
subclass - how should I do this ? (I want to handle the button
differently in the specialised subclasses)
Should I add an actionlistener in the subclass ?? Or is it possible to
overide the actionperformed function registered on the button in the
base class ? (Sun studio 4 makes this function private)
Thanks
Tim
I can think of two ways -- both are bad, though, because they call
virtual (non-final) methods in the constructor. One is to have your
frame implements ActionListener and then override the actionPerformed
method in the subclass. True, your aren't *really* calling a virtual
method in the constructor, but passing 'this' to another method is
basically equivalent. Second, you could make a virtual method to create
an Action for a button -- here's a brief example:
/////////////////////////////////////// Begin ////
import java.awt.event.*;
import javax.swing.*;
public class Tim {
public static void main(String[] args) {
Example1.go();
Example2.go();
}
static class Example1 {
static void go() { show(new SuperFrame()); show(new SubFrame());; }
static class SuperFrame extends JFrame implements ActionListener {
SuperFrame(String s) {
super(s);
JButton b = new JButton("1");
getContentPane().add(b);
b.addActionListener(this);
}
SuperFrame() {this("Super1");}
public void actionPerformed(ActionEvent e) {
System.out.println("Super:"+e);
}
}
static class SubFrame extends SuperFrame {
SubFrame() {super("Sub1");}
public void actionPerformed(ActionEvent e) {
System.out.println("Sub:"+e);
}
}
}
static class Example2 {
static void go() { show(new SuperFrame()); show(new SubFrame());; }
static class SuperFrame extends JFrame {
SuperFrame(String s) {
super(s);
getContentPane().add(new JButton(createAction()));
}
Action createAction() {
return new AbstractAction("2") {
public void actionPerformed(ActionEvent e) {
System.out.println("Super:"+e);
}
};
}
SuperFrame() {this("Super2");}
}
static class SubFrame extends SuperFrame {
SubFrame() {super("Sub2");}
Action createAction() {
return new AbstractAction("2") {
public void actionPerformed(ActionEvent e) {
System.out.println("Super:"+e);
}
};
}
}
}
static void show(JFrame f) {
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
}
/////////////////////////////////////// End ////
Jeff