Exercise 1: Creating The ChatClient GUI Part 2
(Level 3)
In this exercise, you will implement the basic event handlers for the chat
rom application. At this stage in the development of the
ChatClient
GUI, you will need to create the following event listeners listed in
"Exercise 1: Creating the ChatClient GUI Part 2 (Level 1)" on page Lab
11 - 2.
Task 1 -
Modifying the ChatClient
Program
Using a text editor, modify the
ChatClient class source file in the project
directory. This class must implement event listeners listed in
"Exercise 1: Creating the ChatClient GUI Part 2 (Level 1)" on page Lab
11 - 2.
1 . Import the
java.awt.event
package.
- import java.awt.event.*;
- public class ChatClient{
- //your code here
- }
2 . Add the
ActionListener
for the Send button. This listener must extract the text form the text field
and display that text in the text area. Use an inner class for this listener.
- private void launchFrame(){
- //GUI component initalization
code here
- sendButton.addActionListener(new
SendHandler());
- //more code
- }
-
- private class SendHandler implements
ActionListener{
- public void actionPerformed(
ActionEvent e){
-
String text= input.getText();
-
output.setText( output.getText() + text+ "\n");
-
input.setText("");
- }
- }
3. Add the
ActionListener
for teh text filed. Can you use the same listener in Step 2?
- private void launchFrame(){
- //GUI component initalization
code here
- input.addActionListener(new SendHandler());
- //more code
- }
In this solution, the SendHandler inner class was reused to reduce redundant
code.
4. Add the
WindowListener
to the GUI frame. This listener must exit the
ChatClient
program. Use an inner class for this listener.
- private void launchFrame(){
- //GUI component initalization
code here
- frame.addActionListener(new
CloseHandler());
- //more code
- }
-
- private class CloseHandler extents WindowAdapter{
- public void windowClosing (
WindowEvent e ) {
-
System.exit(0);
- }
- }
5. Add the
ActionListener for the Quit button. this
listener must exit the ChatClient program. Use
an anonymous inner class for this listener.
- private void launchFrame(){
- //GUI component initalization
code here
- quitButton.addActionListener(new
ActionListener(){
- public void
actionPerformed( ActionEvent e){
-
System.exit(0);
- }
- } );
- //more code
- }
Notice that in this solution, the
CloseHandler
was not reused because the Quit button requires an ActionListener
rather than a WindowListener. How could you have satisfied
both listener interfaces using the CloseHandler class?.
Task 2 -
Compiling the ChatClient
Program
On the command line, use the
javac command to compile the ChatClient program.
javac
ChatClient.java
Task 3 -
Running the ChatClient
Program
On the command line, use the java
command to run the ChatClient program. Test
the behavior of the event listeners you added.
- java
ChatClient
-