ICS11 Introduction to Computer Programming II - PowerPoint PPT Presentation

1 / 69
About This Presentation
Title:

ICS11 Introduction to Computer Programming II

Description:

JComponent - superclass to most Swing components ... JFrame(String title) sets the title. Method. setTitle( String title ) sets title bar of window ... – PowerPoint PPT presentation

Number of Views:27
Avg rating:3.0/5.0
Slides: 70
Provided by: jayrobertc
Category:

less

Transcript and Presenter's Notes

Title: ICS11 Introduction to Computer Programming II


1
Xavier University Computer Center Sun
Microsystems, Philippines
Java sa Eskwela (JsE) Program
  • ICS11 Introduction to Computer Programming II
  • Joselito dela Cruz Ty

2
Chapter 12
Basic Graphical User Interface Components
3
Outline
  • Swing Overview
  • Java GUI Components
  • JFrame
  • JLabel
  • JTextField and JPasswordField
  • Jbutton
  • JCheckBox and JRadioButton
  • JComboBox
  • Jlist
  • Multiple-Selection Lists
  • Event Handling Model
  • Mouse Event Handling
  • Adapter Classes
  • Keyboard Event Handling

4
GUI Components
  • Graphical User Interface ("Goo-ee")
  • pictorial interface to a program
  • distinctive "look" and "feel"
  • different applications with consistent GUIs
    improve productivity
  • GUIs are built from components
  • component object with which user interacts
  • examples Labels, Text fields, Buttons, Checkboxes

5
GUI Components
  • Swing GUI components
  • defined in package javax.swing
  • original GUI components from Abstract Windowing
    Toolkit in java.awt
  • heavyweight components rely on local platform's
    windowing system for look and feel

6
GUI Components
  • Swing GUI components
  • Swing components are lightweight
  • written in Java, not weighed down by complex GUI
    capabilities of platform
  • more portable than heavyweight components
  • Swing components allow programmer to specify look
    and feel
  • can change depending on platform
  • can be the same across all platforms

7
GUI Components
  • Swing component inheritance hierarchy

8
GUI Components
  • Swing component inheritance hierarchy
  • Component defines methods that can be used in its
    subclasses (for example, paint and repaint)
  • Container collection of related components
  • when using JFrames, attach components to the
    content pane (a Container)
  • method add
  • JComponent - superclass to most Swing components
  • much of a component's functionality inherited
    from these classes

9
GUI Demo
10
JApplet Methods
  • public void init()
  • called when applet is loaded for execution
  • public void start()
  • called after init() and everytime the user
    returns to HTMl page
  • public void paint(Graphics g)
  • called after start() and after every call to
    update() or repaint()
  • public void stop()
  • called when user leaves the webpage
  • public void destroy()
  • called when applet is being removed from memory

11
Class JFrame
  • Is usually extended to make a JFrame object
  • Constructors
  • JFrame() initially invisible
  • JFrame(String title) sets the title
  • Method
  • setTitle( String title )
  • sets title bar of window

12
JLabel
  • provide text instructions on a GUI
  • read-only text
  • programs rarely change a label's contents
  • A JLabel does not react to any users actions

13
JLabel
  • Constructors
  • JLabel()
  • JLabel(Icon image)
  • JLabel(Icon image,int hAlignment)
  • JLabel(String text)
  • JLabel(String txt,Icon i,int hAlignment)
  • JLabel(String text, int hAlignment)
  • Text_Alignment_CONSTANT can be
  • SwingConstants.LEFT
  • SwingConstants.RIGHT
  • SwingConstants.BOTTOM
  • SwingConstants.CENTER

14
JLabel
  • Methods
  • setToolTipText(String s)
  • displays s in a tool tip when mouse over label
  • setText(String text)
  • getText()
  • setIcon(Icon i)
  • setHorizontalTextPosition(int t)
  • setHorizontalAlignment(int t)

15
JLabel
  • Icon
  • Object that implements interface Icon
  • one class is ImageIcon (.gif and .jpeg images)
  • Icon myIconnew ImageIcon("bug1.gif")
  • myLabel.setIcon( myIcon )
  • myLabel.getIcon

16
JTextField
  • single line areas in which text can be entered or
    displayed
  • JPasswordFields show inputted text as an asterisk
  • JPasswordField extends JTextField

17
JTextField
  • Constructors
  • JTextField()
  • JTextField(int columns)
  • JTextField(String text)
  • JTextField(String text,int columns)
  • Methods
  • setText()
  • getText()
  • setEditable(boolean editable )
  • getPassword()

18
JTextArea
  • Constructors
  • JTextArea()
  • JTextField(int rows, int columns)
  • JTextField(String text)
  • JTextField(String text, int rows, int columns)
  • Methods
  • append()
  • getLineCount()
  • insert(String text, int position)
  • setColumns(int columns)
  • setRows()
  • setText()
  • getText()
  • setEditable(boolean editable )

19
Buttons
  • Button
  • a component the user clicks to trigger an action
  • several types of buttons
  • command buttons
  • toggle buttons
  • check boxes
  • radio buttons

20
JButton
  • Command button
  • generates ActionEvent when clicked
  • created with class JButton
  • JButton
  • text on face called button label
  • each button should have a different label
  • support display of Icons

21
JButton
  • Constructors
  • JButton()
  • JButton(Icon a)
  • JButton(String text)
  • JButton(String text, Icon a)
  • Methods of class JButton
  • setRolloverIcon( myIcon )

22
JToggleButton
  • Abstract superclass of state buttons
  • subclasses JCheckBox, JRadioButton
  • have on/off (true/false) values

23
JCheckBox
  • Constructors
  • JCheckBox()
  • JCheckBox(Icon a)
  • JCheckBox(Icon a, boolean selected)
  • JCheckBox(String a)
  • JCheckBox(String a, boolean selected)
  • JCheckBox(String a, Icon a)
  • JCheckBox(String a, Icon a, boolean selected)

24
JCheckBox
  • Methods
  • JCheckBox()
  • JCheckBox(Icon a)
  • JCheckBox(Icon a, boolean selected)
  • JCheckBox(String a)
  • JCheckBox(String a, boolean selected)
  • JCheckBox(String a, Icon a)
  • JCheckBox(String a, Icon a, boolean selected)

25
JRadioButton
  • Radio buttons
  • have two states selected and deselected
  • normally appear as a group
  • only one radio button in the group can be
    selected at time
  • selecting one button turns off the other buttons
    in the same group
  • ButtonGroup - maintains logical relationship
    between radio buttons

26
JRadioButton
  • Constructors
  • JRadioButton()
  • JRadioButton(Icon a)
  • JRadioButton(Icon a, boolean selected)
  • JRadioButton(String text)
  • JRadioButton(String text,boolean slected)
  • JRadioButton(String text, Icon a)
  • JRadioButton(String text, Icon a, boolean
    selected)

27
JRadioButton
  • Class ButtonGroup
  • ButtonGroup myGroup new ButtonGroup()
  • binds radio buttons into logical relationship
  • method add
  • associate a radio button with a group
  • myGroup.add( myRadioButton )

28
JComboBox
  • Drop down list
  • List of items, user makes a selection

29
JComboBox
  • Constructors
  • JComboBox()
  • JComboBox(Object list)
  • Methods
  • numeric index keeps track of elements
  • first element added at index 0
  • first item added appears as currently selected
    item when combo box appears
  • addItem(Object add)
  • insertItemAt(Object a,int index)

30
JComboBox
  • Methods
  • getItemAt(int index)
  • getItemCount()
  • getSelectedIndex()
  • getSelectedItem()
  • getSelectedObjects()
  • removeAllItems()
  • removeItem(Object a)
  • removeItemAt(int index)
  • setEditable(boolean tf)
  • setMaximumRowCount(int count)

31
JList
  • List
  • displays series of items, may select one or more
  • this section, discuss single-selection lists

32
JList
  • Constructors
  • JList()
  • JList(Object listitems)
  • Methods
  • getSelectedIndex()
  • getSelectedIndeces()
  • getSelectedValue()
  • getSelectedValues()
  • getElementAt(int index)
  • setSelectedIndex()
  • setSelectedValue()
  • setListData()
  • setVisibleRowCount(int rows)

33
JScrollPane
  • JScrollPane object used for scrolling
  • takes component to which to add scrolling as
    argument
  • add JScrollPane object to content pane
  • example
  • JList colorListnew JList()4
  • c.add( new JScrollPane(colorList))

34
JList
  • Methods
  • setSelectionMode(selection_CONST)
  • SINGLE_SELECTION
  • one item selected at a time
  • SINGLE_INTERVAL_SELECTION
  • select a contiguous group of items by holding
    Shift key
  • MULTIPLE_INTERVAL_SELECTION
  • select any amount of items
  • hold Ctrl key and click each item to select

35
Layout Managers
  • Layout managers
  • arrange GUI components on a container
  • provide basic layout capabilities
  • easier to use than determining exact size and
    position of every component
  • programmer concentrates on "look and feel" rather
    than details

36
FlowLayout
  • c.setLayout(new FlowLayout())
  • Most basic layout manager
  • components placed left to right in order added
  • when edge of container reached, continues on next
    line
  • components can be left-aligned, centered
    (default), or right-aligned
  • setAlignment( position_CONSTANT )
  • FlowLayout.LEFT, FlowLayout.CENTER,
    FlowLayout.RIGHT

37
Layout Managers
38
BorderLayout
  • c.setLayout(new BorderLayout())
  • default manager for content pane
  • arrange components into 5 regions
  • North, south, east, west, center
  • up to 5 components can be added directly
  • One for each region

39
BorderLayout
  • adding components with BorderLayout layout
    manager
  • c.add(component,position)
  • position BorderLayout.NORTH
  • SOUTH, EAST, WEST, CENTER similar

40
BorderLayout
41
GridLayout
  • c.setLayout(new GridLayout())
  • divides container into a grid
  • components placed in rows and columns
  • all components have same width and height
  • added starting from top left, then from left to
    right
  • when row full, continues on next row, left to
    right

42
GridLayout
  • Constructors
  • GridLayout( rows, columns, hGap, vGap )
  • specify number of rows and columns, and
    horizontal and vertical gaps between elements (in
    pixels)
  • GridLayout( rows, columns )
  • default 0 for hGap and vGap

43
Layout Managers
  • Complex GUIs
  • each component needs to be placed in an exact
    location
  • can use multiple panels
  • each panel's components arranged in a specific
    layout

44
Panels
  • Panels
  • class JPanel inherits from JComponent, which
    inherits from java.awt.Container
  • every JPanel is a Container
  • JPanels can have components (and other JPanels)
    added to them
  • JPanel sized to components it contains
  • grows to accommodate components as they are added

45
Panels
  • Panel Usage
  • create panels, and set the layout for each
  • add components to the panels as needed
  • add the panels to the content pane (default
    BorderLayout)

46
Null Layout Manager
  • c.setLayout(null)
  • No layout manager will be used
  • Position of components will be determined by the
    method
  • component.setBounds(x,y,width,height)

47
GUI Events
  • GUIs are event driven
  • generate events when user interacts with GUI
  • mouse movements, mouse clicks, typing in a text
    field, etc.
  • event information stored in object that extends
    AWTEvent

48
GUI Events
  • To process an event
  • register an event listener
  • Object from a class that implements an
    event-listener interface (from java.awt.event or
    javax.swing.event)
  • e.g. buttonA.addActionListener(this)
  • "Listens" for events
  • implement event handler
  • method that is called in response to an event
  • event handling interface has one or more methods
    that must be defined

49
GUI Events
  • When an event occurs
  • GUI component notifies its listeners
  • calls listener's event handling method
  • Delegation event model
  • use of event listeners in event handling
  • processing of event delegated to particular
    object
  • See eTest2.java

50
GUI Events
  • Registering event listeners
  • all JComponents contain an object of class
    EventListenerList called listenerList
  • when text1.addActionListener(handler) executes
  • new entry placed into listenerList

51
GUI Events
  • Handling events
  • when event occurs, has an event ID
  • component uses this to decide which method to
    call
  • if ActionEvent, then actionPerformed called (in
    all registered ActionListeners)

52
GUI Component Events
  • JLabel
  • does not respond to any event

53
GUI Component Events
  • JTextField, JPasswordField,JButton, JCheckBox,
    JRadioButton
  • ActionListener(ActionEvent e)
  • getActionCommand
  • returns text in JTextField that generated event
    or the labels in JButton, JCheckBox, and
    JRadioButton that generated the event
  • getSource
  • getSource returns a Component reference to
    component that generated event

54
GUI Component Events
  • JCheckBox, JRadioButton, JComboBox
  • ItemEvent generated every time buttons change or
    item is selected
  • handled by an ItemListener, which must define
    itemStateChanged
  • register handlers with addItemListener
  • private class CheckBoxHandler implements
    ItemListener
  • public void itemStateChanged( ItemEvent e )

55
GUI Component Events
  • JCheckBox, JRadioButton, JComboBox
  • Class ItemEvent.getStateChange
  • returns ItemEvent.SELECTED or ItemEvent.DESELECTED

56
GUI Component Events
  • JList
  • ListSelectionListener
  • valueChanged(ListSelectionEvent e)
  • register handler with addListSelectionListener

57
Mouse Events
  • Mouse events
  • can be trapped for any GUI component derived from
    java.awt.Component
  • mouse event handling methods
  • take a MouseEvent object
  • contains info about event, including x and y
    coordinates
  • methods getX and getY
  • MouseListener and MouseMotionListener
  • addMouseListener
  • addMouseMotionListener

58
Mouse Events
  • Interface MouseListener
  • public void mousePressed( MouseEvent e )
  • Mouse pressed on a component
  • public void mouseClicked( MouseEvent e )
  • Mouse pressed and released
  • public void mouseReleased( MouseEvent e )
  • Mouse released
  • public void mouseEntered( MouseEvent e )
  • Mouse enters bounds of component
  • public void mouseExited( MouseEvent e )
  • Mouse leaves bounds of component

59
Mouse Events
  • Interface MouseMotionListener
  • public void mouseDragged( MouseEvent e )
  • Mouse pressed and moved
  • public void mouseMoved( MouseEvent e )
  • Mouse moved when over component

60
Adapter Classes
  • time consuming to define all interface methods
  • MouseListener and MouseMotionListener have seven
    methods
  • What if we only want to use one?
  • Required to define all methods in interface

61
Adapter Classes
  • implements an interface
  • default implementation (empty body) for all
    methods
  • programmer extends adapter class
  • overrides methods he wants to use
  • has "is a" relationship with interface
  • MouseAdapter is a MouseListener

62
Adapter Classes
  • ComponentAdapter ComponentListener
  • ContainerAdapter ContainerListener
  • FocusAdapter FocusListener
  • KeyAdapter KeyListener
  • MouseAdapter MouseListener
  • MouseMotionAdapter MouseMotionListener
  • WindowAdapter WindowListener

63
Mouse Events
  • Class MouseEvent
  • inherits from InputEvent
  • can distinguish between buttons on multi-button
    mouse
  • combination of a mouse click and a keystroke
  • Java assumes every mouse has a left mouse button
  • Alt click center mouse button
  • Meta click right mouse button

64
Mouse Events
  • Class MouseEvent
  • method getClickCount
  • returns number of mouse clicks (separate for each
    button)
  • methods isAltDown and isMetaDown
  • returns true if Alt or Meta key down when mouse
    clicked

65
Keyboard Events
  • Interface KeyListener
  • handles key events (keys pressed on keyboard)
  • must define methods
  • keyPressed - called when any key pressed
  • keyTyped - called when non-action key pressed
  • action keys arrow keys, home, end, page up, page
    down, function keys, num lock, print screen,
    scroll lock, caps lock, pause

66
Keyboard Events
  • Interface KeyListener
  • must define methods (continued)
  • keyReleased - called for any key after it is
    released
  • each get a KeyEvent as an argument
  • subclass of InputEvent

67
Keyboard Events
  • KeyEvent methods
  • getKeyCode
  • every key represented with a virtual key code
    (constant)
  • complete list in on-line documentation
    (java.awt.event)
  • getKeyText
  • takes key code constant, returns name of key

68
Keyboard Events
  • KeyEvent methods
  • getKeyChar
  • gets Unicode character of key pressed
  • isActionKey
  • returns true if key that generated event is an
    action key

69
Keyboard Events
  • KeyEvent methods
  • getModifiers (from class InputEvent)
  • returns which modifiers were pressed
  • getKeyModifierText ( e.getModifiers )
  • returns string containing names of modifier keys
Write a Comment
User Comments (0)
About PowerShow.com