Creating User Interfaces Event-Driven Programming.

46
Creating User Creating User Interfaces Interfaces Event-Driven Event-Driven Programming Programming

Transcript of Creating User Interfaces Event-Driven Programming.

Page 1: Creating User Interfaces Event-Driven Programming.

Creating User InterfacesCreating User Interfaces Event-Driven Programming Event-Driven Programming

Page 2: Creating User Interfaces Event-Driven Programming.

Frequently used GUI components

AbstractButton

JToggleButton

JCheckBox

JRadioButton

JComboBox

JList

JSlider

JTextComponent

JLabel

JButton

Component Container JComponent

JTextField

JTextArea

JScrollBar

Page 3: Creating User Interfaces Event-Driven Programming.

java.awt.Container +add(comp: Component): Component +add(comp: Component, index: int): Component +remove(comp: Component): void +getLayout(): LayoutManager +setLayout(l: LayoutManager): void +paintComponents(g: Graphics): void

Appends a component to the container. Adds a component to the container with the specified index. Removes the component from the container. Returns the layout manager for this container. Sets the layout manager for this container. Paints each of the components in this container.

java.awt.Component +getFont(): java.awt.Font +setFont(f: java.awt.Font): void +getBackground(): java.awt.Color +setBackground(c: Color): void +getForeground(): java.awt.Color +setForeground(c: Color): void +getWidth(): int +getHeight(): int +getPreferredSize(): Dimension +setPreferredSize(d: Dimension) : void +isVisible(): boolean +setVisible(b: boolean): void

Returns the font of this component. Sets the font of this component. Returns the background color of this component. Sets the background color of this component. Returns the foreground color of this component. Sets the foreground color of this component. Returns the width of this component. Returns the height of this component. Returns the preferred size of this component. Sets the preferred size of this component. Indicates whether this component is visible. Shows or hides this component.

javax.swing.JComponent +getToolTipText(): String

+setToolTipText(test: String): void +getBorder(): javax.swing.border.Border +setBorder(border: Border): void

Returns the tool tip text for this component. Tool tip text is displayed when the mouse points on the component without clicking.

Sets a new tool tip text for this component. Returns the border for this component. Sets a new border for this component.

Page 4: Creating User Interfaces Event-Driven Programming.

Borders

You can set a border on any object of the JComponent class. Swing has several types of borders. To create a titled border, use

new TitledBorder(String title)

To create a line border, use new LineBorder(Color color, int width)

For example:JPanel panel = new JPanel();TitleBorder t = new TitleBorder(“MyPanel”);panel.setBorder(t);

Page 5: Creating User Interfaces Event-Driven Programming.

TitledBorder example

• You can change the it’s properties– Change Title color using setTitleColor(Color);– Change Title font using setTitleFont(Font);

Page 6: Creating User Interfaces Event-Driven Programming.

LineBorder example

• You can Create it using:– LineBorder(Color); – LineBorder(Color, thickness); – LineBorder(Color, thickness, rounded);

Page 7: Creating User Interfaces Event-Driven Programming.

Buttons• A button is a component that triggers an

action event when clicked. • Swing provides regular buttons, toggle

buttons, check box buttons, and radio buttons.

• The common features of these buttons are represented in: – javax.swing.AbstractButton.

Page 8: Creating User Interfaces Event-Driven Programming.

javax.swing.AbstractButton +getActionCommand(): String +setActionCommand(s: String): void +getText(): String +setText(text: String): void +getIcon(): javax.swing.Icon +setIcon(icon: Icon): void

+getPressedIcon(): javax.swing.Icon +setPressedIcon(pressedIcon: Icon): void +getRolloverIcon(): javax.swing.Icon +setRolloverIcon(pressedIcon: Icon):

void +getMnemonic(): int

+setMnemonic(mnemonic: int): void +getHorizontalAlignment(): int +setHorizontalAlignment(alignment: int):

void +getHorizontalTextPosition(): int +setHorizontalTextPosition(position: int):

void +getVerticalAlignment(): int +setVerticalAlignment(vAlignment: int):

void +getVerticalTextPosition(): int +setVerticalTextPosition(position: int) :

void +isBorderPainted(): Boolean +setBorderPainted(b: boolean): void

+getIconTextGap(): int +setIconTextGap(iconTextGap: int): void +isSelected(): Boolean

+setSelected(b: boolean): void

Returns the action command of this button. Sets a new action command for this button. Returns the button’s text (i.e., the text label on the button). Sets the button’s text. Returns the button’s default icon. Sets the button's default icon. This icon is also used as the "pressed" and

"disabled" icon if there is no explicitly set pressed icon. Returns the pressed icon (displayed when the button is pressed). Sets a pressed icon for the button. Returns the rollover icon (displayed when the mouse is over the button). Sets a rollover icon for the button.

Returns the mnemonic key value of this button. You can select the button by pressing the ALT key and the mnemonic key at the same time.

Sets a mnemonic key value of this button. Returns the horizontal alignment of the icon and text on the button. Sets the horizontal alignment of the icon and text. (default: CENTER)

Returns the horizontal text position relative to the icon on the button. Sets the horizontal text position of the text relative to the icon. (default:

RIGHT) Returns the vertical alignment of the icon and text on the button. Sets the vertical alignment of the icon and text. (default: CENTER).

Returns the vertical text position relative to the icon on the button. Sets the vertical text position of the text relative to the icon. (default:

CENTER) Indicates whether the border of the button is painted. Draws or hides the border of the button. By default, a regular button’s

border is painted, but the border for a check box and a radio button is not painted.

Returns the gap between the text and the icon on the button. (JDK 1.4) Sets a gap between the text and the icon on the button. (JDK 1.4) Returns the state of the button. True if the check box or radio button is

selected, false if it's not. Sets the state for the check box or radio button.

javax.swing.JComponent

Page 9: Creating User Interfaces Event-Driven Programming.

JButtonJButton inherits AbstractButton and provides several constructors to create buttons.

javax.swing.JButton +JButton() +JButton(icon: javax.swing.Icon) +JButton(text: String) +JButton(text: String, icon: Icon)

Creates a default button with no text and icon. Creates a button with an icon. Creates a button with text. Creates a button with text and an icon.

javax.swing.AbstractButton

Page 10: Creating User Interfaces Event-Driven Programming.

JButton Properties• text• Icon• mnemonic• horizontalAlignment• verticalAlignment• horizontalTextPosition• verticalTextPosition• iconTextGap

Page 11: Creating User Interfaces Event-Driven Programming.

IconsAn icon is a fixed-size picture; typically it is small and used to decorate components.

To create an image, use its concrete class javax.swing.ImageIcon

For example:ImageIcon icon = new ImageIcon("photo.gif");

Page 12: Creating User Interfaces Event-Driven Programming.

JCheckBox

javax.swing.JCheckBox +JCheckBox() +JCheckBox(text: String) +JCheckBox(text: String, selected:

boolean) +JCheckBox(icon: Icon) +JCheckBox(text: String, icon: Icon) +JCheckBox(text: String, icon: Icon,

selected: boolean)

Creates a default check box button with no text and icon. Creates a check box with text. Creates a check box with text and specifies whether the check box is

initially selected. Creates a checkbox with an icon. Creates a checkbox with text and an icon. Creates a check box with text and an icon, and specifies whether the check

box is initially selected.

javax.swing.AbstractButton

javax.swing.JToggleButton

Page 13: Creating User Interfaces Event-Driven Programming.

JRadioButtonRadio buttons are variations of check boxes. They are often used in the group, where only one button is checked at a time.

javax.swing.JRadioButton +JRadioButton() +JRadioButton(text: String) +JRadioButton(text: String, selected:

boolean) +JRadioButton(icon: Icon) +JRadioButton(text: String, icon: Icon) +JRadioButton(text: String, icon: Icon,

selected: boolean)

Creates a default radio button with no text and icon. Creates a radio button with text. Creates a radio button with text and specifies whether the radio button is

initially selected. Creates a radio button with an icon. Creates a radio button with text and an icon. Creates a radio button with text and an icon, and specifies whether the radio

button is initially selected.

javax.swing.AbstractButton

javax.swing.JToggleButton

Page 14: Creating User Interfaces Event-Driven Programming.

Grouping Radio Buttons

ButtonGroup btg = new ButtonGroup();btg.add(jrb1);btg.add(jrb2);

Page 15: Creating User Interfaces Event-Driven Programming.

JLabel

A label is a display area for a short text, an image, or both.

javax.swing.JLabel +JLabel() +JLabel(icon: javax.swing.Icon) +JLabel(icon: Icon, hAlignment: int) +JLabel(text: String) +JLabel(text: String, icon: Icon,

hAlignment: int) +JLabel(text: String, hAlignment: int) +getText(): String +setText(text: String): void +getIcon(): javax.swing.Icon +setIcon(icon: Icon): void +getHorizontalAlignment(): int +setHorizontalAlignment(alignment: int):

void +getHorizontalTextPosition(): int +setHorizontalTextPosition(textPosition:

int): void +getVerticalAlignment(): int +setVerticalAlignment(vAlignment: int):

void +getVerticalTextPosition(): int +setVerticalTextPosition(vTextPosition:

int) : void +getIconTextGap(): int +setIconTextGap(iconTextGap: int): void

Creates a default label with no text and icon. Creates a label with an icon. Creates a label with an icon and the specified horizontal alignment. Creates a label with text. Creates a label with text, an icon and the specified horizontal alignment.

Creates a label with text and the specified horizontal alignment. Returns the label’s text. Sets the label’s text. Returns the label’s image icon. Sets an image icon on the label. Returns the horizontal alignment of the text and icon on the label. Sets the horizontal alignment – same as for buttons.

Returns the horizontal text position relative to the icon on the label. Sets the horizontal text position – same as for buttons.

Returns the vertical alignment of the text and icon on the label. Sets the vertical alignment – same as for buttons.

Returns the vertical text position relative to the icon on the label. Sets the vertical text position – same as for buttons

Returns the gap between the text and the icon on the label. (JDK 1.4) Sets a gap between the text and the icon on the label. (JDK 1.4)

javax.swing.JComponent

Page 16: Creating User Interfaces Event-Driven Programming.

Using Labels// Create an image icon from image fileImageIcon icon = new ImageIcon("image/grapes.gif"); // Create a label with text, an icon, // with centered horizontal alignmentJLabel jlbl = new JLabel("Grapes", icon, SwingConstants.CENTER); // Set label's text alignment and gap between text and iconjlbl.setHorizontalTextPosition(SwingConstants.CENTER);jlbl.setVerticalTextPosition(SwingConstants.BOTTOM);jlbl.setIconTextGap(5);

Page 17: Creating User Interfaces Event-Driven Programming.

JTextFieldA text field is an input area where the usercan type in characters. Text fields are useful in that they enable the user to enter in variable data (such as a name or a description).

javax.swing.JTextField +JTextField() +JTextField(column: int) +JTextField(text: String) +JTextField(text: String, columns: int) +getColumns(): int +setColumns(columns: int): void +getHorizontalAlignment(): int +setHorizontalAlignment(alignment: int): void

Creates a default empty text field with number of columns set to 0. Creates an empty text field with specified number of columns. Creates a text field initialized with the specified text. Creates a text field initialized with the specified text and columns. Returns the number of columns in this text field. Sets the number of columns in this text field. Returns the horizontal alignment of this text field. Sets the horizontal alignment for this text field. (default: LEFT)

javax.swing.text.JTextComponent +getText(): String +setText(text: String): void +isEditable(): boolean +setEditable(b: boolean): void

Returns the text contained in this text component. Sets a text in this text component. Indicates whether this text component is editable. Sets the text component editable or prevents it from being edited.

(default: true)

Page 18: Creating User Interfaces Event-Driven Programming.

JTextAreaIf 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.

javax.swing.JTextArea +JTextArea() +JTextArea(rows: int, columns: int) +JTextArea(text: String) +JTextArea(text: String, rows: int, columns: int) +append(s: String): void +insert(s: String, pos: int): void +replaceRange(s: String, start: int, end: int): void +getColumns(): int +setColumns(columns: int): void +getRows(): int +setRows(rows: int): void +getLineCount(): int +getTabSize(): int +setTabSize(size: int): void +getLineWrap(): Boolean +setLineWrap(wrap: boolean): void +getWrapStyleWord(): Boolean +setWrapStyleWord(word: boolean): void

Creates a default empty text area. Creates an empty text area with the specified number of rows and columns. Creates a new text area with the specified text displayed. Creates a new text area with the specified text and number of rows and columns. Appends the string to text in the text area. Inserts string s in the specified position in the text area. Replaces partial text in the range from position start to end with string s. Returns the number of columns in this text area. Sets the number of columns in this text area. Returns the number of rows in this text area. Sets the number of rows in this text area. Returns the actual number of lines contained in the text area. Returns the number of characters used to expand tabs in this text area. Sets the number of characters to expand tabs to. (default: 8) Indicates whether the line in the text area is automatically wrapped. Sets the line-wrapping policy of the text area. (default: false) Indicates whether the line is wrapped on words or characters. Sets the style of wrapping used if the text area is wrapping lines. The default

value is false, which indicates that the line is wrapped on characters.

javax.swing.text.JTextComponent

Page 19: Creating User Interfaces Event-Driven Programming.

JComboBoxA 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.

javax.swing.JComboBox +JComboBox() +JComboBox(items: Object[]) +addItem(item: Object): void +getItemAt(index: int): Object +getItemCount(): int +getSelectedIndex(): int +setSelectedIndex(index: int): void +getSelectedItem(): Object +setSelectedItem(item: Object): void +removeItem(anObject: Object): void +removeItemAt(anIndex: int): void +removeAllItems(): void

Creates a default empty combo box. Creates a combo box that contains the elements in the specified array. Adds an item to the combo box. Returns the item at the specified index. Returns the number of items in the combo box. Returns the index of the selected item. Sets the selected index in the combo box. Returns the selected item. Sets the selected item in the combo box. Removes an item from the item list. Removes the item at the specified index in the combo box. Removes all items in the combo box.

javax.swing.JComponent

Page 20: Creating User Interfaces Event-Driven Programming.

JListA 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.

javax.swing.JList +JList() +JList(items: Object[]) +getSelectedIndex(): int +setSelectedIndex(index: int): void +getSelectedIndices(): int[] +setSelectedIndices(indices: int[]): void +getSelectedValue(): Object +getSelectedValues(): Object[] +getVisibleRowCount(): int +setVisibleRowCount(count: int): void +getSelectionBackground(): Color +setSelectionBackground(c: Color): void +getSelectionForeground(): Color +setSelectionForeground(c: Color): void +getSelectionMode(): int +setSelectionMode(selectionMode: int):

Creates a default empty list. Creates a list that contains the elements in the specified array. Returns the index of the first selected item. Selects the cell at the specified index. Returns an array of all of the selected indices in increasing order. Selects the cells at the specified indices. Returns the first selected item in the list. Returns an array of the values for the selected cells in increasing index order. Returns the number of visible rows displayed without a scrollbar. (default: 8) Sets the preferred number of visible rows displayed without a scrollbar. Returns the background color of the selected cells. Sets the background color of the selected cells. Returns the foreground color of the selected cells. Sets the foreground color of the selected cells. Returns the selection mode for the list. Sets the selection mode for the list.

javax.swing.JComponent

Page 21: Creating User Interfaces Event-Driven Programming.

21

Procedural vs. Event-Driven Programming

• Procedural programming is executed in procedural order.

• In event-driven programming, code is executed upon activation of events.

Page 22: Creating User Interfaces Event-Driven Programming.

Event-Driven Programming

• code is executed upon activation of 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.

Page 23: Creating User Interfaces Event-Driven Programming.

Event-Driven Programming

• The component on which an event is fired or generated is called the source object or source component.

• For example, a button is the source object for a button-clicking action event.

Page 24: Creating User Interfaces Event-Driven Programming.

Event Classes

The root class of the event classes is java.util.EventObject.

Page 25: Creating User Interfaces Event-Driven Programming.

Event Information

An event object contains whatever properties are pertinent to the event. You can identify the source object of the event using : getSource() instance method in the EventObject class.

Page 26: Creating User Interfaces Event-Driven Programming.

Selected User ActionsUser Action Source Object Event Type Generated

Click a button JButton ActionEventPress return on a text field JTextField ActionEvent

Select a new item JComboBox ItemEvent, ActionEvent

Select item(s) JList ListSelectionEventClick a check box JCheckBox ItemEvent, ActionEvent

Click a radio button JRadioButton ItemEvent, ActionEvent

Select a menu item JMenuItem ActionEventMove the scroll bar JScrollBar AdjustmentEvent

Window opened, closed, etc. Window WindoEvent

Component added or removed from the container

Container ContainerEvent

Component moved, resized, etc.

Component ComponentEvent

Component gained or lost focus

Component FocusEvent

Key released or pressed Component KeyEvent

Mouse pressed, released, clicked, etc.

Component MouseEvent

Mouse moved or dragged Component MouseEvent

Page 27: Creating User Interfaces Event-Driven Programming.

The Delegation Event Model• Model used by Java to handle user

interaction with GUI components• Describes how your program can respond to

user interaction• Three important players

Event Source Event Listener/Handler Event Object

Page 28: Creating User Interfaces Event-Driven Programming.

Event SourceGUI component that generates the eventExample: button

Event Listener/HandlerReceives and handles events.Contains business logic.Example: displaying information useful to

the user, computing a value.

The Delegation Event Model

Page 29: Creating User Interfaces Event-Driven Programming.

Event Object Created when an event occurs (i.e., user

interacts with a GUI component). Contains all necessary information about

the event that has occurred Type of event that has occurred Source of the event

Represented by an Event class

The Delegation Event Model

Page 30: Creating User Interfaces Event-Driven Programming.

• A listener should be registered with a source• Once registered, listener waits until an event

occurs.• When an event occurs

– An event object created by the event source– Event object is fired by the event source to the

registered listeners (method of event listener is called with an event object as a parameter).

• Once the listener receives an event object from the source– Deciphers the event.– Processes the event that occurred.

Event Listener Registers to EventSource

Page 31: Creating User Interfaces Event-Driven Programming.

Control Flow of Delegation Event Model

Page 32: Creating User Interfaces Event-Driven Programming.

Steps for Creating GUI Applicationswith Event Handling

1.Create a GUI class– Describes and displays the appearance of your

GUI application.2.Create Event Listener class (a class

implementing the appropriate listener interface)– Override all methods of the appropriate listener

interface.– Describe in each method how you would like

the event to be handled.– May give empty implementations for methods

you don't need.

Page 33: Creating User Interfaces Event-Driven Programming.

Steps for Creating GUI Applicationswith Event Handling

3.Register the listener object with the event source– The object is an instantiation of the

listener class in step 2.– Use the add<Type>Listener method of

the event source.

Page 34: Creating User Interfaces Event-Driven Programming.

Selected Event Handlers

Page 35: Creating User Interfaces Event-Driven Programming.

java.awt.event.ActionEvent

java.awt.event.ActionEvent +getActionCommand(): String

+getModifier(): int +getWhen(): long

Returns the command string associated with this action. For a button, its text is the command string.

Returns the modifier keys held down during this action event. Returns the timestamp when this event occurred. The time is

the number of milliseconds since January 1, 1970, 00:00:00 GMT.

java.util.EventObject +getSource(): Object

Returns the object on which the event initially occurred.

java.awt.event.AWTEvent

Page 36: Creating User Interfaces Event-Driven Programming.

Handling Simple Action EventsExample

• Write a program that displays two buttons OK and Cancel in the window.

• A message is displayed on the console to indicate which button is clicked and when a button is clicked.

Page 37: Creating User Interfaces Event-Driven Programming.

MouseEvent

java.awt.event.MouseEvent +getButton(): int +getClickCount(): int +getPoint(): java.awt.Point +getX(): int +getY(): int

Indicates which mouse button has been clicked. Returns the number of mouse clicks associated with this event. Returns a Point object containing the x and y coordinates. Returns the x-coordinate of the mouse point. Returns the y-coordinate of the mouse point.

java.awt.event.InputEvent +getWhen(): long +isAltDown(): boolean +isControlDown(): boolean +isMetaDown(): boolean +isShiftDown(): boolean

Returns the timestamp when this event occurred. Returns whether or not the Alt modifier is down on this event. Returns whether or not the Control modifier is down on this event. Returns whether or not the Meta modifier is down on this event Returns whether or not the Shift modifier is down on this event.

Page 38: Creating User Interfaces Event-Driven Programming.

Handling Mouse Events• Java provides two listener interfaces, MouseListener and MouseMotionListener, 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.

Page 39: Creating User Interfaces Event-Driven Programming.

Handling Mouse Events

java.awt.event.MouseListener

+mousePressed(e: MouseEvent): void

+mouseReleased(e: MouseEvent): void

+mouseClicked(e: MouseEvent): void

+mouseEntered(e: MouseEvent): void +mouseExited(e: MouseEvent): void

Invoked when the mouse button has been pressed on the source component.

Invoked when the mouse button has been released on the source component.

Invoked when the mouse button has been clicked (pressed and released) on the source component.

Invoked when the mouse enters the source component. Invoked when the mouse exits the source component.

java.awt.event.MouseMotionListener

+mouseDragged(e: MouseEvent): void +mouseMoved(e: MouseEvent): void

Invoked when a mouse button is moved with a button pressed. Invoked when a mouse button is moved without a button

pressed.

Page 40: Creating User Interfaces Event-Driven Programming.

Example Moving Message Using MouseObjective: Create a program to display a message in a panel. You can use the mouse to move the message. The message moves as the mouse drags and is always displayed at the mouse point.

Page 41: Creating User Interfaces Event-Driven Programming.

Example Handling Complex Mouse Events

Objective: Create a program for drawing using a mouse. Draw by dragging with the left mouse button pressed; erase by dragging with the right button pressed.

Page 42: Creating User Interfaces Event-Driven Programming.

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:

Page 43: Creating User Interfaces Event-Driven Programming.

The KeyEvent Class• Methods:getKeyChar() method

getKeyCode() method

• Keys:Home VK_HOMEEnd VK_EndPage Up VK_PGUPPage Down VK_PGDNetc...

Page 44: Creating User Interfaces Event-Driven Programming.

The KeyEvent Class, cont.

java.awt.event.KeyEvent +getKeyChar(): char +getKeyCode(): int

Returns the character associated with the key in this event. Returns the integer keyCode associated with the key in this event.

java.awt.event.InputEvent

Page 45: Creating User Interfaces Event-Driven Programming.

ExampleKeyboard Events Demo

Objective: Display a user-input character. The user can also move the character up, down, left, and right using the arrow keys.

Page 46: Creating User Interfaces Event-Driven Programming.

Thank YouThank You