CSCI213 Spring2013 Lectures Java GUI

download CSCI213 Spring2013 Lectures Java GUI

of 17

Transcript of CSCI213 Spring2013 Lectures Java GUI

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    1/17

    1

    Java GUI Basics

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Objectives

    Introduction to java GUI basics To distinguish between Swing and AWT To describe the Java GUI API hierarchy To create user interfaces using frames, panels, and

    simple GUI components

    To understand the role of layout managers To use the FlowLayout, GridLayout, and BorderLayout

    managers to layout components in a container To use JPanel as subcontainers To specify colors and fonts using the Color and Font

    classes

    To apply common features such as borders, tool tips,fonts, and colors on Swing components

    2

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Graphical user interface (GUI)

    Presents a user-friendly mechanism forinteracting with an application Often contains title bar, menu bar

    containing menus, buttons and comboboxes

    Built from GUI components

    3

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    2/17

    2

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Elements of GUI Programming

    ComponentsVisual objects that appear on the screen

    Layouts Control over the positioning of components

    within a container

    Events Responses to user actions

    Graphics Lines, shapes, colors, fonts, etc.

    All are encapsulated in Java Classes and Packages4

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Graphical Componentsbutton menus title bar menu bar combo box

    scroll

    bars

    5

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    mp e - ase nput utputwith JOptionPane

    Dialog boxes Used by applications to interact with the user Provided by Javas JOptionPane class

    Contains input dialogs and message dialogs

    6

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    3/17

    3

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    1 // Example!2 // Addition program that uses JOptionPane for input and output.!3 import javax.swing.JOptionPane; // program uses JOptionPane !4 !5 public class Addition6 {7 public static void main( String args[] )8 {9 // obtain user input from JOptionPane input dialogs !10 String firstNumber =11 JOptionPane.showInputDialog( "Enter first integer" );12 String secondNumber =13 JOptionPane.showInputDialog( "Enter second integer" );14 !15 // convert String inputs to int values for use in a calculation!16 int number1 = Integer.parseInt( firstNumber );17 int number2 = Integer.parseInt( secondNumber );18 !19 int sum = number1 + number2; // add numbers !20 !21 // display result in a JOptionPane message dialog !22 JOptionPane.showMessageDialog( null, "The sum is " + sum,23 "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE );24 } // end method main !25 } // end class Addition !

    Show input dialog to receive first

    integer

    Show input dialog to receive

    second integer

    Show message dialog to output sum

    to user

    Example

    7

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Input dialog displayed by lines 1011

    Input dialog displayed by lines 1213

    Message dialog displayed by lines 2223

    Text field in which

    the user types a

    value

    Prompt to the user

    hen the user clicksOK,showInputDialog returns

    to the program the100typed by the user as a

    String . The programmust convert the String

    to an int

    title bar

    When the user clicksOK,the

    message dialog is dismissed

    (removed from the screen)

    Example (2)

    8

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    JOptionPane static constants

    Message dialog type Icon Description

    ERROR_MESSAGE A dialog that indicates an error to the user.

    INFORMATION_MESSAGE A dialog with an informational message t o theuser.

    WARNING_MESSAGE A dialog warning the user of a potentialproblem.

    QUESTION_MESSAGE A dialog that poses a question to the user. Thisdialog normally requires a response, s uch as

    clicking aYes or a No button.

    PLAIN_MESSAGE no icon A dialog that contains a message, but no icon.

    9

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    4/17

    4

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Most Used Components

    Component Description

    JLabel Displays uneditable text or icons.JTextField Enables user to enter data from the keyboard. Can also be used to

    display editable or uneditable text.

    JButton Triggers an event when clicked with the mouse.JCheckBox Specifies an option that can be selected or not selected.JComboBox Provides a drop-down list of items from which the user can make a

    selection by clicking an item or possibly by typing into the box.

    JList Provides a list of items from which the user can make a selection byclicking on any item in the list. Multiple elements can be selected.

    JPanel Provides an area in which components can be placed and organized.Can also be used as a drawing area for graphics.

    10

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Creating GUI Objects// Create a button with text OKJButton jbtOK = new JButton("OK");

    // Create a label with text "Enter your name: "

    JLabel jlblName = new JLabel("Enter your name: ");

    // Create a text field with text "Type Name Here"

    JTextField jtfName = new JTextField("Type Name Here");

    // Create a check box with text boldJCheckBox jchkBold = new JCheckBox("Bold");

    // Create a radio button with text red

    JRadioButton jrbRed = new JRadioButton("Red");

    // Create a combo box with choices red, green, and blue

    JComboBox jcboColor = new JComboBox(new String[]{"Red","Green", "Blue"});

    Button

    Label Textfield

    CheckBox

    RadioButton

    ComboBox

    11

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Swing vs. AWT So why do the GUI component classes have a prefix J?

    Q: instead of JButton, why not name it simply Button?

    A: there is a class already named Button in the java.awt package When Java was introduced, the GUI classes were bundled in a library known as

    the Abstract Windows Toolkit (AWT).

    For every platform on which Java runs, the AWT components are automaticallymapped to the platform-specific components through their respective agents,known as peers

    AWT is fine for developing simple graphical user interfaces, but not fordeveloping comprehensive GUI projects

    Besides, AWT is prone to platform-specific bugs its peer-based approach relies heavily on the underlying platform.

    With the release of Java 2, the AWT user-interface components were replacedby a more robust, versatile, and flexible library known as Swing components

    Swing components are less dependent on the target platform and use less ofthe native GUI resource. For this reason, Swing components that dont rely onnative GUI are referred to as lightweight components, and AWT componentsare referred to as heavyweight components.

    12

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    5/17

    5

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    GUI Class Hierarchy (Swing)

    13

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Container Classes

    14

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    GUI Helper Classes

    The helper classes are notsubclasses of Component. Theyare used to describe theproperties of GUI componentssuch as colors, fonts, anddimension.

    15

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    6/17

    6

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Swing GUI Components

    16

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    omponents overe n t e r eVersion

    17

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    omponents overe n t eComprehensive Version

    18

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    7/17

    7

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    AWT (Optional)

    19

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Frames

    Frame is a window that is not containedinside another window. Frame is the basisto contain other user interfacecomponents in Java GUI applications.

    The JFrame class can be used to createwindows.

    For Swing GUI programs, use JFrame classto create widows.

    20

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Frames with Components

    A Frame is a container. Therefore it can containother components (like buttons, text fields, etc.) Components are added to the content pane of a

    frame.

    The content pane is the grey area in the Framewindow.

    A simplistic way to look at containment is this:A JFrame contains:

    A menu barA content pane

    21

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    8/17

    8

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    A Picture of Frame Containment

    22

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Creating Framesimport javax.swing.*;public class MyFrame {

    public static void main(String[] args) {

    JFrame frame = new JFrame("Test Frame");frame.setSize(400, 300);

    frame.setVisible(true);frame.setDefaultCloseOperation(

    JFrame.EXIT_ON_CLOSE);

    }}!

    23

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Adding Components into a Frame!// Add a button into the frameframe.getContentPane().add(

    new JButton("OK"));Title bar

    Contentpane

    24

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    9/17

    9

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Content Pane Delegation in JDK1.5!

    // Add a button into the frameframe.getContentPane().add(

    new JButton("OK"));Title bar

    Contentpane

    // Add a button into the frameframe.add(

    new JButton("OK"));

    25

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Adding a JButton to a Frameimport javax.swing.*;public class MyFrame {

    public static void main(String[] args) {

    JFrame frame = new JFrame("Test Frame");

    JButton okBtn = new Jbutton(Ok));

    frame.add(okBtn);

    frame.setSize(400, 300);

    frame.setVisible(true);frame.setDefaultCloseOperation(

    JFrame.EXIT_ON_CLOSE);

    }}!

    26

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    JFrame Classjavax.swing.JFrame

    +JFrame()

    +JFrame(title: String)

    +setSize(width: int, height: int): void

    +setLocation(x: int, y: int): void

    +setVisible(visible: boolean): void

    +setDefaultCloseOperation(mode: int): void

    +setLocationRelativeTo(c: Component):

    void

    +pack(): void

    Creates a default frame with no title.

    Creates a frame with the specified title.

    Specifies the size of the frame.

    Specifies the upper-left corner location of the frame.

    Sets true to display the frame.

    Specifies the operation when the frame is closed.

    Sets the location of the frame relative to the specified component.

    If the component is null, the frame is centered on the screen.

    Automatically sets the frame size to hold the components in the

    frame.

    27

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    10/17

    10

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Layout Managers

    Javas layout managers provide a level of abstraction toautomatically map your user interface on all windowsystems.

    Control the placement of components on the container. The UI components are placed in containers. Each

    container has a layout manager to arrange the UIcomponents within the container.

    This is an alternative to hardcoding the pixel locations ofthe components.

    Advantage: resizing the container (frame) will notocclude or distort the view of the components.

    Layout managers are set in containers using thesetLayout(LayoutManager) method in a container.

    28

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Kinds of Layout Managers

    Basic layouts: FlowLayout GridLayout BorderLayout

    Other layout managers: Containers Layout Managers, and Borders

    29

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    FlowLayout Places components sequentially (left-to-right) in

    the order they were added

    Components will wrap around if the width of thecontainer is not wide enough to hold them all in arow.

    Default for applets and panels, but not for frames Options:

    left, center (this is the default), or right Typical syntax: in your Frame classs constructor

    setLayout(new FlowLayout(FlowLayout.LEFT)) OR setLayout(new

    FlowLayout(FlowLayout.LEFT,hgap,vgap))

    30

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    11/17

    11

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Resizing the frame causes thecomponents to wrap aroundwhen necessary.

    31

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    The FlowLayout Class

    java.awt.FlowLayout

    -alignment: int

    -hgap: int

    -vgap: int

    +FlowLayout()

    +FlowLayout(alignment: int)

    +FlowLayout(alignment: int, hgap:int, vgap: int)

    The alignment of this layout manager (default: CENTER).

    The horizontal gap of this layout manager (default: 5 pixels).

    The vertical gap of this layout manager (default: 5 pixels).

    Creates a default FlowLayout manager.

    Creates a FlowLayout manager with a specified alignment.

    Creates a FlowLayout manager with a specified alignment,horizontal gap, and vertical gap.

    The get and set methods for these data fields are provided inthe class, but omitted in the UML dia ram for brevit .

    32

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    GridLayout

    Arranges components into rows and columns In Frames constructor: setLayout (new GridLayout(rows, columns))

    OR

    setLayout(new GridLayout(rows,columns,hgap,vgap)) Components will be added in order, left to right,

    row by row

    Components will be equal in sizeAs container is resized, components will resize

    accordingly, and remain in same grid

    arrangement

    33

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    12/17

    12

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Resizing the frame causes thecomponents to resize andmaintain their same grid pattern.

    34

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    The GridLayout Class

    java.awt.GridLayout

    -rows: int

    -columns: int

    -hgap: int

    -vgap: int

    +GridLayout()

    +GridLayout(rows: int, columns: int)

    +GridLayout(rows: int, columns: int,hgap: int, vgap: int)

    The number of rows in this layout manager (default: 1).

    The number of columns in this layout manager (default: 1).

    The horizontal gap of this layout manager (default: 0).

    The vertical gap of this layout manager (default: 0).

    Creates a default GridLayout manager.

    Creates a GridLayout with a specified number of rows and columns.

    Creates a GridLayout manager with a specified number of rows andcolumns, horizontal gap, and vertical gap.

    The get and set methods for these data fields are provided inthe class, but omitted in the UML diagram for brevity.

    35

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    BorderLayout Arranges components into five areas: North, South, East,

    West, and Center In the constructor:

    setLayout(new BorderLayout())OR

    setLayout(new BorderLayout(hgap,vgap)) for each component:

    add (the_component, region) do for each area desired:

    BorderLayout.EAST, BorderLayout.SOUTH, BorderLayout.WEST,BorderLayout.NORTH, or BorderLayout.CENTER

    Behavior: when the container is resized, the componentswill be resized but remain in the same locations.

    NOTE: only a maximum of five components can beadded and seen in this case, one to each region.

    36

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    13/17

    13

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Resizing the

    frame causesthe componentsto resize andmaintain theirsame regions.

    NOTE: the CENTER regiondominates the sizing.

    37

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    The BorderLayoutClass

    java.awt.BorderLayout

    -hgap: int

    -vgap: int

    +BorderLayout()

    +BorderLayout(hgap: int, vgap: int)

    The horizontal gap of this layout manager (default: 0).

    The vertical gap of this layout manager (default: 0).

    Creates a default BorderLayout manager.

    Creates a BorderLayout manager with a specified number of

    horizontal gap, and vertical gap.

    The get and set methods for these data fields are provided inthe class, but omitted in the UML diagram for brevity.

    38

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Using Panels as Sub-Containers

    JPanel is a class of special components that cancontain other components.As containers, JPanels can have their own layout

    managers.

    This way, you can combine layouts within thesame frame by adding panels to the frame andby adding other components to the panels.

    Therefore, like JFrames, you can use thesemethods with JPanels:

    add() to add components to the panel setLayout() to associate a layout manager for the

    panel39

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    14/17

    14

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Testing Panels

    This example uses panels to organizecomponents. The program creates a userinterface for a Microwave oven.

    A button

    A textfield

    12

    buttons

    frame

    p2

    p1

    40

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    The Color ClassYou can set colors for GUI components by using thejava.awt.Color class. Colors are made of red, green,and blue components, each of which is representedby a byte value that describes its intensity, rangingfrom 0 (darkest shade) to 255 (lightest shade). Thisis known as the RGB model.

    Color c = new Color(r, g, b);r,g, and

    bspecify a color by its red, green, and

    blue components. !Example:

    Color c = new Color(228, 100, 255);

    45

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Standard ColorsThirteen standard colors (black, blue, cyan, darkGray,

    gray, green, lightGray, magenta, orange, pink, red,white, yellow) are defined as constants in

    java.awt.Color.

    The standard color names are constants, but they arenamed as variables with lowercase for the first wordand uppercase for the first letters of subsequent words.Thus the color names violate the Java namingconvention.

    Since JDK 1.4, you can also use the new constants:BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN,LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE,and YELLOW.

    46

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    15/17

    15

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Setting Colors

    You can use the following methods to set thecomponents background and foreground colors:

    setBackground(Color c)

    setForeground(Color c)

    Example:

    jbt.setBackground(Color.yellow);

    jbt.setForeground(Color.red);

    47

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    The Font Class

    Font myFont = new Font(name, style, size);

    Example:Font myFont = new Font("SansSerif ", Font.BOLD, 16);Font myFont = new Font("Serif", Font.BOLD+Font.ITALIC, 12);

    JButton jbtOK = new JButton("OK);

    jbtOK.setFont(myFont);

    Font NamesStandard font namesthat are supported inall platforms are:SansSerif, Serif,Monospaced, Dialog,or DialogInput.

    Font StyleFont.PLAIN (0),Font.BOLD (1),Font.ITALIC (2), andFont.BOLD +Font.ITALIC (3)

    48

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Finding All Available Font

    NamesGraphicsEnvironment e =

    GraphicsEnvironment.getLocalGraphicsEnvironment();

    String[] fontnames =e.getAvailableFontFamilyNames();

    for (int i = 0; i < fontnames.length; i++)

    System.out.println(fontnames[i]);

    49

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    16/17

    16

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Using Panels as Sub-Containers

    Panels act as sub-containers for grouping userinterface components.

    It is recommended that you place the userinterface components in panels and place the

    panels in a frame. You can also place panels in a

    panel.

    To add a component to JFrame, you actually addit to the content pane of JFrame. To add a

    component to a panel, you add it directly to the

    panel using the add method.

    50

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Creating a JPanel

    You can use new JPanel() to create a panel with adefault FlowLayout manager or new

    JPanel(LayoutManager) to create a panel with the

    specified layout manager

    Use the add(Component) method to add acomponent to the panel. For example,

    JPanel p = new JPanel();

    p.add(new JButton("OK"));

    51

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Testing Panels Example

    This example uses panels to organizecomponents. The program creates a userinterface for a Microwave oven.!

    52

  • 7/30/2019 CSCI213 Spring2013 Lectures Java GUI

    17/17

    17

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Common Features of Swing Components

    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

    Adds 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

    -font: java.awt.Font

    -background: java.awt.Color

    -foreground: java.awt.Color

    -preferredSize: Dimension

    -visible: boolean

    +getWidth(): int

    +getHeight(): int

    +getX(): int

    +getY(): int

    The font of this component.

    The background color of this component.

    The foreground color of this component.

    The preferred size of this component.

    Indicates whether this component is visible.

    Returns the width of this component.

    Returns the height of this component.

    getX() and getY() return the coordinate of the components

    upper-left corner within its parent component.

    javax.swing.JComponent

    -toolTipText: String

    -border: javax.swing.border.Border

    The tool tip text for this component. Tool tip text is displayed when

    the mouse points on the component without clicking.

    The border for this component.

    The get and set methods for these data fields are provided in

    the class, but omitted in the UML diagram for brevity.

    The get and set methods for these data fields are provided in

    the class, but omitted in the UML diagram for brevity.

    53

    CSE

    UOWD

    CSCI 213: Java GUISpring 2013

    Image IconsJava uses the javax.swing.ImageIcon class torepresent an icon. An icon is a fixed-size picture;

    typically it is small and used to decoratecomponents. Images are normally stored in imagefiles. You can use new ImageIcon(filename) toconstruct an image icon. For example, the followingstatement creates an icon from an image file abc.gif

    in the image directory under the current class path:ImageIcon icon = new ImageIcon("image/abc.gif");

    56