"Inheriting" from multiple classes
Previous
Next
Java Source
// The problem: I would like class U to inherit the click service of class
// Aservicer but I choose to inherit services from JPanel. No problem:
// I can create an object of class Aservicer and use that object to invoke
// the methods of Aservicer that I need.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
// A provider of a click recording service - an object of this class
// provides a panel and will record the position of mouse clicks in
// the panel. The service provided is to return the coordinates of
// the last click in the panel.
class Aservicer1 extends JPanel implements MouseListener {
int x,y; // last known mouse coordinates on which a click occurred
public Aservicer1 () { addMouseListener(this); }
public void mouseClicked (MouseEvent evt) {
x = evt.getX();
y = evt.getY();
System.out.println("Aservicer: X="+x+" Y="+y);
}
public void mouseEntered (MouseEvent evt) {}
public void mouseExited (MouseEvent evt) {}
public void mousePressed (MouseEvent evt) {}
public void mouseReleased (MouseEvent evt) {}
public int getX () { return x; }
public int getY () { return y; }
}
// Want to make use of the click service above
class U1 extends JFrame implements ActionListener {
JTextField x,y;
JButton a;
Aservicer1 s; // Get an Aservicer1 object
public U1 () {
setLayout(new GridLayout(2,1));
add(s = new Aservicer1());
JPanel p = new JPanel();
p.setLayout(new GridLayout(1,2));
p.add(x = new JTextField());
p.add(y = new JTextField());
JPanel q = new JPanel();
q.setLayout(new GridLayout(2,1));
q.add(p);
q.add(a = new JButton("Get Click Point"));
add(q);
a.addActionListener(this);
}
public void actionPerformed (ActionEvent evt) {
if (evt.getSource() == a) {
x.setText(String.valueOf(s.getX())); // Use the Aservicer1 methods
y.setText(String.valueOf(s.getY()));
}
}
}
public class Prog1 extends Applet {
public void init () {
U1 u1 = new U1();
u1.setSize(180,140);
u1.setVisible(true);
}
}