creating user interfaces event-driven programming
TRANSCRIPT
Creating User InterfacesCreating User Interfaces Event-Driven Programming Event-Driven Programming
Frequently used GUI components
AbstractButton
JToggleButton
JCheckBox
JRadioButton
JComboBox
JList
JSlider
JTextComponent
JLabel
JButton
Component Container JComponent
JTextField
JTextArea
JScrollBar
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.
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);
TitledBorder example
• You can change the it’s properties– Change Title color using setTitleColor(Color);– Change Title font using setTitleFont(Font);
LineBorder example
• You can Create it using:– LineBorder(Color); – LineBorder(Color, thickness); – LineBorder(Color, thickness, rounded);
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.
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
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
JButton Properties• text• Icon• mnemonic• horizontalAlignment• verticalAlignment• horizontalTextPosition• verticalTextPosition• iconTextGap
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");
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
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
Grouping Radio Buttons
ButtonGroup btg = new ButtonGroup();btg.add(jrb1);btg.add(jrb2);
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
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);
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)
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
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
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
21
Procedural vs. Event-Driven Programming
• Procedural programming is executed in procedural order.
• In event-driven programming, code is executed upon activation of events.
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.
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.
Event Classes
The root class of the event classes is java.util.EventObject.
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.
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
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
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
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
• 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
Control Flow of Delegation Event Model
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.
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.
Selected Event Handlers
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
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.
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.
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.
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.
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.
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.
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_HOMEEnd VK_EndPage Up VK_PGUPPage Down VK_PGDNetc...
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
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.
Thank YouThank You