Sei sulla pagina 1di 6

Object-Oriented Programming Laboratory (Java Lab) ITS 103 ICT SIIT Boontawee Suntisrivaraporn (sun@siit.tu.ac.

th)

Lab 9 - Event-Driven Programming

Lab objectives
To understand the concept of event-driven programming. To be able to design and build usable Graphical User Interfaces. To appreciate the benets of object-oriented design paradigm in Java GUI and event-driven programming, especially inheritance and polymorphism.

Event-Driven Programming
In this lab, we continue to practice GUI development and practice event-driven programming which is capable of responding to events generated by the user. We start with learning the Java interface ActionListener. This interface declares one method, i.e. actionPerformed() as follows: public interface ActionListener extends ... { void actionPerformed(ActionEvent e); } We can dene a class that implements this interface to specify what actions to do. In order to attach an ActionListener object to a GUI component, use the addActionListener method. The following example demonstrate how to do this: Example 1 Go to the course Website1 and download the Java source MoveMessagePanel.java to your workstation. Create a new project called Lab9-Example1. Add the downloaded Java le to the source folder. Then, compile and run the program. Try to understand the following: How is ActionListener used? Where is its method implemented? How are actions attached to the GUI components? Exercise 1: Using ActionListener Create a new Java project called Lab9-Exercise1. Modify the following GUI application so that it actually converts miles to kilometers when pressing the Convert! button. Note that you need to implement the ActionListener interface and override the actionPerformed() method. To change a display text on the JText component, you can use the method setText(...). Note that 1 mile is equal to 1.609 kilometers. Your output from this program should look similar to Figure 1. import javax.swing.*; import java.awt.*; public class Converter extends JFrame { private JLabel prompt = new JLabel("Distance in miles: "); private JTextField input = new JTextField(6); private JTextArea display = new JTextArea(10,20); private JButton convert = new JButton("Convert!"); private JPanel p1 = new JPanel(new FlowLayout());
1 http://ict.siit.tu.ac.th/

~ sun/dw/doku.php?id=its103

Figure 1: A sample output of Exercise 1. private final double KMS_PER_MILE = 1.609; public Converter() { super("Distance Converter"); setLayout(new BorderLayout()); p1.add(prompt); p1.add(input); p1.add(convert); add(p1, BorderLayout.NORTH); add(display, BorderLayout.CENTER); } public static void main(String args[]) { Converter f = new Converter(); f.setSize(400, 300); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } } Exercise 2: Changing background colors (optional; do only after you nish Exercise 5) Create a new Java project called Lab9-Exercise2. White a program that changes the background color when a user clicks one of the three buttons labeled with the names of dierent colors: red, green and blue. In this exercise, you need to: 1. Create an inner class ActionHandler embeded in the original class. Make the ActionHandler a child class of the interface ActionListener, i.e. ActionHandler implements ActionListener. 2. Override the abstract method in ActionHandler that is inherited from ActionListener. When a button is pressed, change the background color of the panel according to the buttons label. 3. Attach an object of ActionHandler to the three button components. Your output program should look similar to Figure 2. Exercise 3: Moving the snowman Create a new Java project called Lab9-Exercise3. Write a program that draws a snowman on a panel. The position of the snowman can be changed using the control buttons. With the four buttons, a user can move the snowman to the left, right, up or down position. Your output should look similar to Figure 3. You may copy and modify the following source code:

Figure 2: A sample output of Exercise 2. import java.awt.*; import javax.swing.JFrame; import javax.swing.JPanel; public class MovingSnowman extends JPanel { int midX = 220; int midY = 280; public void paintComponent(Graphics g) { super.paintComponent(g); setBackground(new Color(40,144,0)); g.setColor (Color.yellow); g.fillArc (-40, -40, 80, 80, 0, -90); g.setColor g.fillOval g.fillOval g.fillOval

// sun

(Color.white); (midX-20, midY-60, 40, 40); (midX-35, midY-25, 70, 50); (midX-50, midY+20, 100, 60);

// head // upper body // lower body

g.setColor (Color.black); g.fillOval (midX-10, midY-50, 5, 5); // left eye g.fillOval (midX+5, midY-50, 5, 5); // right eye g.drawArc (midX-10, midY-40, 20, 10, 190, 160); // smile g.drawLine (midX-25, midY, midX-50, midY-20); // left arm g.drawLine (midX+25, midY, midX+55, midY); // right arm g.drawLine (midX-20, midY-55, midX+20, midY-55); // brim of hat g.fillRect (midX-15, midY-80, 30, 25); // hat } public static void main(String args[]) { JFrame frame = new JFrame("Moving Snowman");

Figure 3: A sample output of Exercise 3. frame.add(new MovingSnowman()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500,500); frame.setVisible(true); } }

Handling Key Events


KeyListener is another of the several event handlers provided in the java.awt library. This interface species three methods for handling events generated by the keyboard, known as the class KeyEvent. The three abstract methods are keyPressed(), keyTyped() and keyReleased(), all of which take an object of type KeyEvent. When implementing KeyListener, all these methods must be overridden. In case that no action is to be dened for certain event, you can provide the empty body to the method as follows: public void keyTyped(KeyEvent e) Exercise 4: Using the keyboard Continue from Exercise 3. Modify the program so that the user can move the position of the snowman using the up, down, left or right arrow key. In this exercise, you need to: 1. Make the MovingSnowMan class a child class of the KeyListener interface, i.e. MovingSnowMan implements KeyListener. 2. Override the three abstract methods from KeyListener. (a) In keyPressed(), compare key code that it is pressed whether it is up, down, left or right arrow key using the method getKeyCode() of the KeyEvent class. The key codes of the up, down, left and right arrows are 38, 40, 37 and 39, respectively. (b) Provide the empty implementation for the other two inherited methods. 3. Move the the snowman to the assigned direction and redraw it at the new location. 4. Attach the KeyListener implementation to the panel using the method addKeyListener. { }

Handling Mouse Events


There are two types of mouse events. The rst one is mouse motion events which are triggered by moving the mouse pointer, and the other one is regular mouse events which are triggered by clicking the mouse buttons or by moving the mouse pointer into or out of a components area. The two types of mouse events are specied in the Java interfaces MouseMotionListener and MouseListener, respectively. Example 2 Go to the course Website and download the Java source ScribblePanel.java to your workstation. Create a new project called Lab9-Example2. Add the downloaded Java le to the source folder. Then, compile and run the program. This example illustrates how to use MouseListener and MouseMotionListener. A user can draw arbitrary lines by dragging the mouse pointer over the panel. To erase any drawn lines, press the right button and drag the mouse pointer over those lines. Exercise 5: Using MouseListener and MouseMotionListener Create a new project called Lab9-Exercise5. Write a program that shows a square. The user will be able to drag it with the mouse. To support dragging, you have to implement both the MouseListener and MouseMotionListener interfaces and register the JPanel to listen to both mouse and mouse motion events. The code for dragging a square should be spread out over three methods, mousePressed, mouseReleased and mouseDragged. Note that you have to check whether the clicked position falls within the rectangle. If so, move the rectangle to a new dragging position. Otherwise, it takes no eect. In this exercise, you need to: 1. Create an inner class MouseClickHandler embedded in the original class. Make the MouseClickHandler a child class of the interface MouseListener. 2. Override the abstract methods from MouseListener. Get the location of the mouse pointer and check whether it falls within the rectangle. 3. Create an inner class MouseMotionHandler embedded in the original class. Make the MouseMotionHandler a child class of the interface MouseMotionListener. 4. Override the abstract methods from MouseListener. If the user presses the mouse button on the rectangle, and it is being dragged, move the rectangle to the new dragging position by redrawing the rectangle at this location. Otherwise, do nothing. 5. In the constructor of the original class, create listener objects named clickHandler and motionHandler which are instances of MouseClickHandler and MouseMotionHandler, respectively. Register them to the panel using the methods addMouseListener and addMouseMotionListener. You may copy and modify the following source code. Your output should look similar to Figure 4. import java.awt.*; import javax.swing.JFrame; import javax.swing.JPanel; public class DragSquare extends JPanel { int x1, y1; int length = 30; public DragSquare() { x1 = 220; y1 = 220; } public void paintComponent(Graphics g) { super.paintComponent(g);

Figure 4: A sample output of Exercise 5. A user will be able to drag a square with the mouse. g.setColor(Color.red); g.fillRect(x1, y1, length, length); } public static void main(String args[]) { JFrame frame = new JFrame("Dragging Square"); frame.add(new DragSquare()); frame.setSize(500,500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }

Potrebbero piacerti anche