1 / 47

SD1420 Unit 10

SD1420 Unit 10. Chapter 16 Event-Driven Programming Chapter 17 GUI Components. Objectives. To describe events, event sources, and event classes To define listener classes using inner classes To write programs to deal with MouseEvent s

phong
Download Presentation

SD1420 Unit 10

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. SD1420Unit 10 Chapter 16 Event-Driven ProgrammingChapter 17 GUI Components

  2. Objectives • To describe events, event sources, and event classes • To define listener classes using inner classes • To write programs to deal with MouseEvents • To simplify coding for listener classes using listener interface adapters • To write programs to deal with KeyEvents • To use the javax.swing.Timer class to control animations • To create graphical user interfaces with various user-interface components • To create listeners for JCheckBox, JRadioButton, and JTextField • To display multiple windows in an application

  3. Procedural vs. Event-Driven Programming • Procedural programming is executed in procedural order. • In event-driven programming, code is executed upon activation of events.

  4. Trace Execution public class HandleEvent extends JFrame { public HandleEvent() { … OKListenerClass listener1 = new OKListenerClass(); jbtOK.addActionListener(listener1); … } public static void main(String[] args) { … } } class OKListenerClass implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("OK button clicked"); } } 1. Start from the main method to create a window and display it.

  5. Trace Execution public class HandleEvent extends JFrame { public HandleEvent() { … OKListenerClass listener1 = new OKListenerClass(); jbtOK.addActionListener(listener1); … } public static void main(String[] args) { … } } class OKListenerClass implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("OK button clicked"); } } 2. Click OK.

  6. Trace Execution 3. Click OK. The JVM invokes the listener’s actionPerformed method. public class HandleEvent extends JFrame { public HandleEvent() { … OKListenerClass listener1 = new OKListenerClass(); jbtOK.addActionListener(listener1); … } public static void main(String[] args) { … } } class OKListenerClass implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("OK button clicked"); } }

  7. Events • An event can be defined as a type of signal to the program that something has happened. • The event is generated by external user actions such as mouse movements, mouse clicks, and keystrokes, or by the operating system, such as a timer.

  8. Event Classes

  9. Event Information An event object contains whatever properties are pertinent to the event. You can identify the source object of the event using the getSource() instance method in the EventObject class. The subclasses of EventObject deal with special types of events, such as button actions, window events, component events, mouse movements, and keystrokes. Table 16.1 on page 603 lists external user actions, source objects, and event types generated.

  10. Selected User Actions Source Event TypeUser Action Object Generated Click a button JButtonActionEvent Click a check box JCheckBoxItemEvent, ActionEvent Click a radio button JRadioButtonItemEvent, ActionEvent Press return on a text field JTextFieldActionEvent Select a new item JComboBoxItemEvent, ActionEvent Window opened, closed, etc. WindowWindowEvent Mouse pressed, released, etc. ComponentMouseEvent Key released, pressed, etc. ComponentKeyEvent

  11. The Delegation Model

  12. Internal Function of a Source Component

  13. The Delegation Model: Example JButton jbt = new JButton("OK"); ActionListener listener = new OKListener(); jbt.addActionListener(listener);

  14. Selected Event Handlers Event Class Listener Interface Listener Methods (Handlers)ActionEvent ActionListener actionPerformed(ActionEvent) ItemEvent ItemListener itemStateChanged(ItemEvent) WindowEvent WindowListener windowClosing(WindowEvent) windowOpened(WindowEvent) windowIconified(WindowEvent) windowDeiconified(WindowEvent) windowClosed(WindowEvent) windowActivated(WindowEvent) windowDeactivated(WindowEvent) ContainerEvent ContainerListener componentAdded(ContainerEvent) componentRemoved(ContainerEvent) MouseEvent MouseListener mousePressed(MouseEvent) mouseReleased(MouseEvent) mouseClicked(MouseEvent) mouseExited(MouseEvent) mouseEntered(MouseEvent) KeyEvent KeyListener keyPressed(KeyEvent) keyReleased(KeyEvent) keyTypeed(KeyEvent)

  15. java.awt.event.ActionEvent

  16. Inner Class Listeners A listener class is designed specifically to create a listener object for a GUI component (e.g., a button). It will not be shared by other applications. So, it is appropriate to define the listener class inside the frame class as an inner class.

  17. Inner Classes Inner class: A class is a member of another class. Advantages: In some applications, you can use an inner class to make programs simple. • An inner class can reference the data and methods defined in the outer class in which it nests, so you do not need to pass the reference of the outer class to the constructor of the inner class.

  18. Inner Classes, cont.

  19. Inner Classes (cont.) • Inner classes can make programs simple and concise. • An inner class supports the work of its containing outer class and is compiled into a class named OuterClassName$InnerClassName.class. For example, the inner class InnerClass in OuterClass is compiled into OuterClass$InnerClass.class.

  20. Inner Classes (cont.) • An inner class can be declared public, protected, or private subject to the same visibility rules applied to a member of the class. • An inner class can be declared static. A static inner class can be accessed using the outer class name. A static inner class cannot access nonstatic members of the outer class.

  21. Anonymous Inner Classes • An anonymous inner class must always extend a superclass or implement an interface, but it cannot have an explicit extends or implements clause. • An anonymous inner class must implement all the abstract methods in the superclass or in the interface. • An anonymous inner class always uses the no-arg constructor from its superclass to create an instance. If an anonymous inner class implements an interface, the constructor is Object(). • An anonymous inner class is compiled into a class named OuterClassName$n.class. For example, if the outer class Test has two anonymous inner classes, these two classes are compiled into Test$1.class and Test$2.class.

  22. Anonymous Inner Classes (cont.) Inner class listeners can be shortened using anonymous inner classes. An anonymous inner class is an inner class without a name. It combines declaring an inner class and creating an instance of the class in one step. An anonymous inner class is declared as follows: new SuperClassName/InterfaceName() { // Implement or override methods in superclass or interface // Other methods if necessary }

  23. MouseEvent

  24. Handling Mouse Events • Java provides two listener interfaces, MouseListener andMouseMotionListener, to handle mouse events. • The MouseListener listens for actions such as when the mouse is pressed, released, entered, exited, or clicked. • The MouseMotionListener listens foractions such as dragging or moving themouse.

  25. Handling Mouse Events

  26. Handling Keyboard Events • keyPressed(KeyEvent e) Called when a key is pressed. • keyReleased(KeyEvent e) Called when a key is released. • keyTyped(KeyEvent e) Called when a key is pressed and thenreleased. To process a keyboard event, use the following handlers in the KeyListener interface:

  27. The KeyEvent Class • Methods: getKeyChar() method getKeyCode() method • Keys: Home VK_HOME End VK_END Page Up VK_PGUP Page Down VK_PGDN etc...

  28. The KeyEvent Class, cont.

  29. The Timer Class Some non-GUI components can fire events. The javax.swing.Timer class is a source component that fires an ActionEvent at a predefined rate. The Timer class can be used to control animations. For example, you can use it to display a moving message.

  30. JTextArea If you want to let the user enter multiple lines of text, you cannot use text fields unless you create several of them. The solution is to use JTextArea, which enables the user to enter multiple lines of text.

  31. JTextArea Constructors • JTextArea(int rows, int columns) Creates a text area with the specified number of rows and columns. • JTextArea(String s, int rows, int columns) Creates a text area with the initial text andthe number of rows and columns specified.

  32. JTextArea Properties • text • editable • columns • lineWrap • wrapStyleWord • rows • lineCount • tabSize

  33. Example: Using Text Areas • This example gives a program that displays an image in a label, a title in a label, and a text in a text area.

  34. JComboBox A combo box is a simple list of items from which the user can choose. It performs basically the same function as a list, but can get only one value.

  35. JComboBox Methods To add an item to a JComboBox jcbo, use jcbo.addItem(Object item) To get an item from JComboBox jcbo, use jcbo.getItem()

  36. Using the itemStateChangedHandler public void itemStateChanged(ItemEvent e) { // Make sure the source is a combo box if (e.getSource() instanceof JComboBox) String s = (String)e.getItem(); } When a choice is checked or unchecked, itemStateChanged() for ItemEvent is invoked as well as the actionPerformed() handler for ActionEvent.

  37. JList A list is a component that performs basically the same function as a combo box, but it enables the user to choose a single value or multiple values.

  38. JList Constructors • JList() Creates an empty list. • JList(Object[] stringItems) Creates a new list initialized with items.

  39. JList Properties • selectedIndexd • selectedIndices • selectedValue • selectedValues • selectionMode • visibleRowCount

  40. JScrollBar A scroll bar is a control that enables the user to select from a range of values. The scrollbar appears in two styles: horizontal and vertical.

  41. Scroll Bar Properties

  42. JSlider JSlider is similar to JScrollBar, but JSlider has more properties and can appear in many forms.

  43. Creating Multiple Windows The following slides show step-by-step how to create an additional window from an application or applet as referenced from the book page 660 Section 17.8.

  44. Creating Additional Windows, Step 1 • Step 1: Define a main class for the frame named MultiWindowDemo. Add a text are inside a scroll pane, and place the scroll pane in the center of the frame. Create a button Show Histogram and place it in the south of the frame.

  45. Creating Additional Windows, Step 2 Step 2: Define a subclass of Jpanel named Histogram. The class contains a data field named count of the int[] type, which counts the occurrences of 26 letters. The values in count are displayed in the histogram.

  46. Creating Additional Windows, Step 3 Step 3: Implement the actionPerformed handler in MultipleWindowsDemo, as follows. A: Create an instance of Histogram. Count the letters in the text area and set the count in the Histogram object. B: Create a new frame and place the Histogram object in the center of the frame. Display the frame.

  47. Summary In this presentation the following areas were covered: • Event Driven Programming • Inner Class Listeners • Mouse Event • Keyboard Event • Timer Class • Multiple Windows

More Related