|20-CS-694||Advanced Programming Techniques||Spring 2012|
All applets have a JButton that says 'Press Me'. Hit that button.
||An attribute of object-oriented languages is the ability to inherit services from other classes. In Java this is handled by extends. In the code to the left class java_2Frame inherits the ability to display a JTextArea and JButton from the JFrame class.|
||But a class can use services of another class by creating an object of that class and then by invoking methods on that object. This is done to the left with JFrame. The change from the above is to eliminate extends from java_3Frame, add JFrame f, and then add f. where the services of a JFrame are required.|
||In the previous example it is OK to create a JFrame object to provide JFrame services instead of inheriting from JFrame because the JFrame object does not need to send results back to java_3Frame. However, in numerous cases a callback is necessary. For example, when the JButton is clicked, the event it causes must be sent back to java_3Frame to be processed, in that case by actionPerformed. The ActionListener interface provides a guarantee that the appropriate method will be available to receive this callback. But even this is not necessary as the code to the left shows. Class java_4Frame neither extends a class nor implements an interface yet it acts on a button press and it displays a window. To achieve this another class called AListener is written. An object l of this class is instantiated in the constructor of java_4Frame in the same way that JFrame object f is except with this as an argument. Then l.addAlistener(go) is invoked instead of go.addActionListener(this) as in the previous code example. This time java_4Frame provides the guarantee that a callback procedure, namely action, will be available to the AListener class.|
||The usual way to achieve callback is through the use of inner classes. The code to the left achieves the same result as the code above. The inner class solution exploits direct access to the widgets of the java_5Frame class.|
Question: Is it possible for an interfaced service provider to
broadcast responses to a number of clients?
Answer: Yes. The code to the left uses a JButton as service provider. When the button is pressed, a signal is sent to three class A objects. Each object is associated with a JFrame and a JTextField. A message unique to each object is printed in its JTextField.