02 gui new 4spp

Upload: luong-dinh-thap

Post on 03-Apr-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 02 Gui New 4spp

    1/22

    03/01/2013

    1

    Graphics User Interface

    By V Vn Hi

    Faculty of Information Technologies

    Industrial University of Ho Chi Minh City

    Java Programming Course

    Java SE 7 Platform at a Glance

    2

    What is JFC?

    The Java Foundation Classes (JFC) are a comprehensive set of

    GUI components and services to simplifythe development and

    deployment of commercial-quality desktop applications.

    Its an effort to provide a complete CLASS LIBRARY to build

    modern GUIs out-of-the-box.

    With JFCyoull get most of what you need when developing any

    kind of user interface.

    3

    JFC

    4SWING IS FOR GUI BUILDING

  • 7/28/2019 02 Gui New 4spp

    2/22

    03/01/2013

    2

    What about AWT?

    Provides the basic functionality for GUI building.

    Provides a minimum set of components. Complex GUI require complex applications.

    Components difficult to customize extend.

    JFC extends AWT

    JFC provides more components and more functionality.

    AWT provides:

    o The Event Model.

    o The Component/Container conceptualization.

    5

    AWT

    6

    AWT & SWING

    7

    Java GUI History

    Abstract Windowing Toolkit (AWT): Sun's initial effort to create

    a set of cross-platform GUI classes. (JDK 1.0 - 1.1)

    o Maps general Java code to each operating system's real GUI system.

    o Problems: Limited to lowest common denominator; clunky to use.

    Swing: A newer GUI library written from the ground up that allows

    much more powerful graphics and GUI construction. (JDK 1.2+)

    o Paints GUI controls itself pixel-by-pixel rather than handing off to OS.

    o Benefits: Features; compatibility; OO design.

    o Problem: Both exist in Java now; easy to get them

    mixed up; still have to use both in various places.

  • 7/28/2019 02 Gui New 4spp

    3/22

    03/01/2013

    3

    Graphical User Interfaces

    A Graphical User Interface (GUI) in Java is

    created with at least three kinds of objects:

    o Components

    o Events

    o Listeners

    Graphical User Interfaces -Components

    There are two types of Components:

    o Components, which are objects that represent screen

    elements : labels, buttons, text fields, menus, etc.

    o Some components are containersthat hold and organize

    other components: frames, panels, applets, dialog boxes,

    top-level container: frames, windows, dialogs,applets

    containers: panel, tabled panes,scroll panes,

    10

    Java

    Swing

    Components

    11

    12

  • 7/28/2019 02 Gui New 4spp

    4/22

    03/01/2013

    4

    GUI - Events and Listeners (1)

    The Event Model GUI Building is Event Driven.

    Listeners are objects which are notified whenever a certain

    event happens.

    Different Listeners can listen to different events (mouse move,

    button clicks, list selection, windows closing, etc)

    Each component has a list of Listeners for each type of events

    may happen.

    If you want to do something when a certain event happens:

    o Create your listener class/object

    o Register it with the component you are interested in

    13

    GUI - Events and Listeners (2)

    Component

    A component objectmay generate an event

    Listener

    A corresponding listenerobject is designed torespond to the event

    Event

    When the event occurs, the component callsthe appropriate method of the listener,

    passing an object that describes the event

    15

    GUI - Events and Listeners (3)

    Determining Event Sources

    o Recall that interactive GUIs require establishing a relationship

    between components and the listeners that respond to

    component events

    o One listener object can be used to listen to two different

    components

    o The source of the event can be determined by using the

    getSource method of the event passed to the listener

    16

  • 7/28/2019 02 Gui New 4spp

    5/22

    03/01/2013

    5

    GUI Development

    Generally we use components and events that are predefined by

    classes in the Java class library

    Therefore, to create a Java program that uses a GUI we must:

    o instantiate and set up the necessary components

    o implement listener classes for any events we care about

    o establish the relationship between listeners and components that

    generate the corresponding events

    Let's now explore some new components and see how this all comes

    together

    GUI components: Top-level container

    18

    Top-level container: JFrame

    19

    Top-level container: JDialog

    20

  • 7/28/2019 02 Gui New 4spp

    6/22

    03/01/2013

    6

    Top-level container: Window

    21

    Top-level container: JApplet

    22

    Top-level container: Events

    23

    Registe WindowListener

    Top-level container: Events (2)

    24

  • 7/28/2019 02 Gui New 4spp

    7/22

    03/01/2013

    7

    GUI Components - JPanel

    A panelis a container that cannot be displayed on its own but isused to organize other components

    A panel must be added to another container to be displayed Nested Panels

    o Containers that contain other components make up the containment

    hierarchyof an interface

    o This hierarchy can be as intricate as needed to create the visual

    effect desired

    o The following example nests two panels inside a third panel note the

    effect this has as the frame is resized

    25 26

    GUI Components - JPanel

    GUI Components - JLabel

    A label is a GUI component that displays a line of text

    Labels are usually used to display information or identify other

    components in the interface

    It can also be used to display an image. That is, a label can be

    composed of text, and image, or both at the same time

    The ImageIcon class is used to represent an image that is stored in

    a label

    The position of the text relative to the image can be set explicitly

    The alignment of the text and image within the label can be set as

    well

    27 28

    GUI Components - JLabel

  • 7/28/2019 02 Gui New 4spp

    8/22

    03/01/2013

    8

    GUI Components - JButton

    29

    JButton is a clickable region for

    causing actions to occur

    JButtondemo

    30

    Event code organiszation

    There are 3 ways to organize event code:

    o Anonymous class

    Apply when the manipulation code is simple, small

    o Make container implements the listeners (or extends

    adaptor)

    Apply when the manipulation code is medium

    o Make new class for event manipulation

    Apply when the manipulation code is large

    31See demo

    GUI Components - JCheckBox

    A check boxis a button that can be toggled on or off

    It is represented by the JCheckBox class

    Unlike a push button, which generates an action event, a check boxgenerates an item eventwhenever it changes state (is checked on

    or off)

    The ItemListener interface is used to define item event listeners

    The check box calls the itemStateChanged method of the listener

    when it is toggled

    32

  • 7/28/2019 02 Gui New 4spp

    9/22

    03/01/2013

    9

    GUI Components - JRadioButton

    A group of radio buttonsrepresents a set of mutually exclusive

    options only one can be selected at any given time

    When a radio button from a group is selected, the button that is

    currently "on" in the group is automatically toggled off

    To define the group of radio buttons that will work together,

    each radio button is added to a ButtonGroupobject

    A radio button generates an action event

    33

    JRadioButton &JCheckBox demo

    34

    35

    GUI Components JMenu

    A menu offers options to user. Menus are not generally added to user interface. Menu usually appears either in a menubar or as a popupmenu. A JFrame often has a menu bar containing many menus; and each

    menu can contain many choices.

    Menu bar can be added to a JFrame with the methodsetJMenuBar.

    36

  • 7/28/2019 02 Gui New 4spp

    10/22

    03/01/2013

    10

    GUI Components JPopupMenu

    37

    GUI Components JToolBar

    In user interfaces, a toolbar is often used to hold commands

    that also appear in the menus.

    Frequently used commands are placed in a toolbar for quick

    access. Clicking a command in the toolbar is faster than choosing

    it from the menu.

    38

    Layout Managers

    A layout manager is an object that determines the way that

    components are arranged in a container

    There are several predefined layout managers defined in the

    Java standard class library:

    39

    Defined in the AWT

    Defined in Swing

    Flow LayoutBorder LayoutCard LayoutGrid LayoutGridBag LayoutBox LayoutOverlay Layout

    Layout Managers

    Every container has a default layout manager, but we can

    explicitly set the layout manager as well

    Each layout manager has its own particular rules governing howthe components will be arranged

    Some layout managers pay attention to a component's preferred

    size or alignment, while others do not

    A layout manager attempts to adjust the layout as components

    are added and as containers are resized

    40

  • 7/28/2019 02 Gui New 4spp

    11/22

    03/01/2013

    11

    Flow Layout

    Flow layoutputs as many components as possible on a row, thenmoves to the next row

    Rows are created as needed to accommodate all of thecomponents

    Components are displayed in the order they are added to thecontainer

    Each row of components is centered horizontally in the windowby default, but could also be aligned left or right

    Also, the horizontal and vertical gaps between the componentscan be explicitly set

    41

    FLowLayout demo

    42

    Border Layout

    A border layoutdefines five areas into which components can be

    added

    Each area displays one component (which could be a container such

    as a JPanel)

    Each of the four outer areas enlarges as needed to accommodate

    the component added to it

    If nothing is added to the outer areas, they take up no space and

    other areas expand to fill the void

    The center area expands to fill space as needed

    43

    Border Layout demo

    44

  • 7/28/2019 02 Gui New 4spp

    12/22

    03/01/2013

    12

    Grid Layout

    Agrid layoutpresents a containers components in a rectangular

    grid of rows and columns

    One component is placed in each cell of the grid, and all cells

    have the same size

    As components are added to the container, they fill the grid

    from left-to-right and top-to-bottom (by default)

    The size of each cell is determined by the overall size of the

    container

    45

    Grid Layout demo

    46

    Box Layout

    A box layoutorganizes components horizontally (in one row) or

    vertically (in one column)

    Components are placed top-to-bottom or left-to-right in the

    order in which they are added to the container

    By combining multiple containers using box layout, many

    different configurations can be created

    Multiple containers with box layouts are often preferred to one

    container that uses the more complicated gridbag layout

    manager

    47

    Box Layout

    Invisible componentscan be added to a box layout container to

    take up space between components

    o Rigid areashave a fixed size

    o Glue specifies where excess space should go

    A rigid area is created using the createRigidAreamethod of

    the Box class

    Glue is created using the createHorizontalGlue or

    createVerticalGluemethods

    48

    / /

  • 7/28/2019 02 Gui New 4spp

    13/22

    03/01/2013

    13

    Box Layout demo

    49 50

    GUI Components Text component

    51

    GUI Components Text component

    52

    03/01/2013

  • 7/28/2019 02 Gui New 4spp

    14/22

    03/01/2013

    14

    Group Description Swing Classes

    TextControls Also known simply as text fields, textcontrols can display only one line of editabletext. Like buttons, they generate actionevents. Use them to get a small amount oftextual information from the user andperform an action after the text entry iscomplete.

    JTextField and itssubclassesJPasswordField andJFormattedTextField

    PlainTextAreas

    JTextArea can display multiple lines ofeditable text. Although a text area candisplay text in any font, all of the text is inthe same font. Use a text area to allow theuser to enter unformatted text of any lengthor to display unformatted help information.

    JTextArea

    GUI Components Text component

    53

    Group Description Swing Classes

    StyledTextAreas

    A styled text component can display editabletext using more than one font. Some styledtext components allow embedded images andeven embedded components. Styled textcomponents are powerful and multi-facetedcomponents suitable for high-end needs, andoffer more avenues for customization than theother text components. Because they are sopowerful and flexible, styled text componentstypically require more initial programming toset up and use. One exception is that editorpanes can be easily loaded with formatted textfrom a URL, which makes them useful fordisplaying uneditable help information.

    JEditorPaneand its subclassJTextPane

    GUI Components Text component

    54

    55Demo JEditorPane as a simple browser

    More on Event-Handling

    56

    03/01/2013

    http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/JFormattedTextField.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/JFormattedTextField.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/JFormattedTextField.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/JFormattedTextField.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/JEditorPane.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/JTextPane.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/JTextPane.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/JEditorPane.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/JFormattedTextField.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/JFormattedTextField.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/JPasswordField.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.html
  • 7/28/2019 02 Gui New 4spp

    15/22

    03/01/2013

    15

    GUI Components others container

    JScrollPane

    JSplitPane

    JTabbedPane

    57

    Dialog Boxes

    A dialog box is a small window that "pops up" to interact with the

    user for a brief, specific purpose

    The JOptionPane class makes it easy to create dialog boxes for

    presenting information, confirming an action, or accepting an input

    value.

    Dialog types:

    o JOptionPane.showConfirmDialog

    o JOptionPane.showInputDialog

    o JOptionPane.showMessageDialog

    o JOptionPane.showOptionDialog

    58

    Dialog Boxes Input Dialog

    59

    Dialog Boxes Confirm Dialog

    60

    03/01/2013

  • 7/28/2019 02 Gui New 4spp

    16/22

    03/01/2013

    16

    Dialog Boxes Message Dialog

    JOptionPane.INFORMATION_MESSAGE

    JOptionPane.ERROR_MESSAGE

    JOptionPane.PLAIN_MESSAGE

    JOptionPane.WARNING_MESSAGE

    JOptionPane.QUESTION_MESSAGE61

    Dialog Boxes Option Dialog

    62

    Dialog Boxes - JColorChooser

    63

    Dialog Boxes - JFileChooser

    64

    03/01/2013

  • 7/28/2019 02 Gui New 4spp

    17/22

    03/01/2013

    17

    Dialog Boxes - JFileChooser

    65

    Dialog Boxes - JFileChooser

    66

    Choosing multiple file types

    GUI Components others components

    JProgressBar

    JSlider

    JSrollBar

    67

    GUI Components JList

    The Swing Jlist class represents a list of items from which theuser can choose.

    The contents of a JList object can be specified using an arrayof objects.

    A JList object generates a list selection eventwhen the currentselection changes.

    A JList object can be set so that multiple items can be selectedat the same time. It can be one of three options:

    o Single selection only one item can be selected at a time.o Single interval selection multiple, contiguous items can be

    selected at a time.o Multiple interval selection any combination of items can be

    selected.

    The list selection mode is defined by a ListSelectionModelobject.

    68

    03/01/2013

  • 7/28/2019 02 Gui New 4spp

    18/22

    03/01/2013

    18

    69

    GUI Components JTable

    Tables are used to display data in a spreadsheet fashion

    The JFC JTable is oriented toward displaying database recordsin which each row displays a row in the database, and each

    column displays different records values for the same field.

    JTable is a user-interface component that presents data in a

    two-dimensional table format

    The JTable has many features that make it possible to

    customize its rendering and editing but provides defaults for

    these features.

    70

    GUI Components JTable

    A JTable consists of:o Rows of data

    o Columns of data

    o Column headers

    o An editor, if you want cells to be editableo A TableModel, usually a subclass of AbstractTableModel, which stores the

    tables data

    o A TableColumnModel, usually DefaultTableColumnModel, which controls the

    behavior of the tables columns and gives access to the TableColumns

    o A ListSelectionModel, usually DefaultListSelectionModel, which keeps

    track of the JTables currently selected row(s)

    o A TableCellRenderer, usually an instance of DefaultCellRenderer

    o Multiple TableColumns, which store graphical information about each column

    o A JTableHeaderwhich displays column headers

    71

    CreateJTable

    72

    03/01/2013

  • 7/28/2019 02 Gui New 4spp

    19/22

    03/01/2013

    19

    GUI Components Jtable

    73

    JTable: Sort and Filter

    74

    GUI Components JTree

    JTree is a Swing component that displays data in a treelike hierarchy.

    75

    Root

    Leaf

    GUI Components JTree

    While JTree displays the tree, the data representation of the

    tree is handled by TreeModel, TreeNode, and TreePath.

    o TreeModel represents the entire tree,

    o TreeNode represents a node,o TreePath represents a path to a node.

    Unlike the ListModel or TableModel, the tree model does not

    directly store or manage tree data. Tree data are stored and

    managed in TreeNode and TreePath.

    You can create a tree using its no-arg constructor, a tree model,

    a tree node, a Hashtable, an array, or a vector

    76

    03/01/2013

  • 7/28/2019 02 Gui New 4spp

    20/22

    03/01/2013

    20

    GUI Components JTree

    77

    javax.swing.JTree

    -model: TreeModel

    -anchorPath: TreePath

    -leadPath: TreePath

    -selectionModel: TreeSelectionModel

    -cellEditor: TreeCellEditor

    -cellRenderer: TreeCellEditor

    TreeModel

    TreeSelectionModel

    TreeCellRenderer

    TreeNode

    TreeCellEditor

    DefaultTreeModel MutableTreeNode

    TreePath

    DefaultMutableTreeNode

    DefaultTreeCellRenderer

    DefaultTreeCellEditor

    DefaultTreeSelectionModel

    The TreeSelectionModelinterface handles treenode selection.

    The DefaultTreeCellRendererclass provides a default treenode renderer that can display alabel and/or an icon in a node.

    TheDefaultTreeCellEditorcan be used to edit thecells in a text field.

    GUI Components Jtree

    While TreeModel represents the entire tree, TreeNode stores a single

    node of the tree.

    MutableTreeNode defines a subinterface of TreeNode with additionalmethods for changing the content of the node, for inserting and removing a

    child node, for setting a new parent, and for removing the node itself.

    DefaultMutableTreeNode is a concrete implementation of

    MutableTreeNode that maintains a list of children in a vector and provides

    the operations for creating nodes, for examining and modifying a nodes

    parent and children, and also for examining the tree to which the node

    belongs.

    Normally, you should use DefaultMutableTreeNode to create a tree node.

    78

    Demo JTree

    79

    GUI Components JTree : events

    JTreecan fire TreeSelectionEvent and TreeExpansionEvent, among

    many other events.

    Whenever a new node is selected, JTree fires a TreeSelectionEvent.

    Whenever a node is expanded or collapsed, JTree fires a

    TreeExpansionEvent.

    To handle the tree-selection event, a listener must implement the

    TreeSelectionListener interface, which contains a single handler

    named valueChanged method.

    TreeExpansionListenercontains two handlers named treeCollapsed

    and treeExpanded for handling node expansion or node closing.

    80

    03/01/2013

  • 7/28/2019 02 Gui New 4spp

    21/22

    03/01/2013

    21

    JTree event sample 81

    GUI Components JTreeTree Node Rendering and Editing

    82

    MDI - multiple document interface

    Many applications present information in multiple windows that

    are all contained inside a large frame.

    If you minimize the application frame, then all of its windows

    are hidden at the same time.

    In the Windows environment, this user interface is sometimes

    called the multiple document interface or MDI.

    In the world of Java, where you can't rely on a rich host

    windowing system, it makes a lot of sense to have your

    application manage its frames.

    83 84

    03/01/2013

  • 7/28/2019 02 Gui New 4spp

    22/22

    03/01/2013

    Look-and-Feel

    85

    Somes installed look-n-feel:javax.swing.plaf.metal.MetalLookAndFeeljavax.swing.plaf.nimbus.NimbusLookAndFeel com.sun.java.swing.plaf.motif.MotifLookAndFeel com.sun.java.swing.plaf.windows.WindowsLookAndFeel com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel 86