470 likes | 569 Views
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
E N D
SD1420Unit 10 Chapter 16 Event-Driven ProgrammingChapter 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 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
Procedural vs. Event-Driven Programming • Procedural programming is executed in procedural order. • In event-driven programming, code is executed upon activation of events.
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.
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.
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"); } }
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.
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.
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
The Delegation Model: Example JButton jbt = new JButton("OK"); ActionListener listener = new OKListener(); jbt.addActionListener(listener);
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)
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.
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.
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.
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.
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.
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 }
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.
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:
The KeyEvent Class • Methods: getKeyChar() method getKeyCode() method • Keys: Home VK_HOME End VK_END Page Up VK_PGUP Page Down VK_PGDN etc...
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.
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.
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.
JTextArea Properties • text • editable • columns • lineWrap • wrapStyleWord • rows • lineCount • tabSize
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.
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.
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()
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.
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.
JList Constructors • JList() Creates an empty list. • JList(Object[] stringItems) Creates a new list initialized with items.
JList Properties • selectedIndexd • selectedIndices • selectedValue • selectedValues • selectionMode • visibleRowCount
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.
JSlider JSlider is similar to JScrollBar, but JSlider has more properties and can appear in many forms.
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.
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.
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.
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.
Summary In this presentation the following areas were covered: • Event Driven Programming • Inner Class Listeners • Mouse Event • Keyboard Event • Timer Class • Multiple Windows