+ All Categories
Home > Documents > Chapter 2.1 Basic GUI Components

Chapter 2.1 Basic GUI Components

Date post: 04-Apr-2018
Category:
Upload: pabburahati
View: 230 times
Download: 0 times
Share this document with a friend

of 32

Transcript
  • 7/30/2019 Chapter 2.1 Basic GUI Components

    1/32

    F5105Interactive Java Programming

    Chapter 2.1:-

    Basic GUI Components

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    2/32

    Outline

    Objectives Introduction

    JLabel

    JTextFields and JPasswordField

    JButton

    JCheckBox and JRadioButton

    JComboBox

    JList Multiple-Selection Lists

    Event Handling Model

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    3/32

    Mouse Event Handling Mouse Event Adapter Classes

    Keyboard Event Handling

    FlowLayout Layout Manager

    BorderLayout Layout Manager

    GridLayout Layout Manager

    Panels

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    4/32

    Objectives

    To understand the designprinciples of graphical userinterfaces

    To be able to buildgraphical user interfaces

    To understand thepackages containing GUIcomponents and event handling classes and interfaces

    To be able to create and manipulate buttons labels,

    lists, text fields and panels

    To understand mouse events and keyboard events

    To understand and be able to use layout managers.

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    5/32

    Introduction

    A GUI give program a

    distinctive look and feel

    Example in IE window with

    some of its GUI components

    menu bar (File, Edit,

    View, ..)

    buttons

    text field (user can type)

    label (to the left of text

    field)

    ButtonLabel

    Menu

    Menu bar

    Text field

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    6/32

    GUIs are buildfrom GUI components:

    Component DescriptionJLabel Uneditable text/icon area

    JtextField Area user inputs data from keyboard

    JButton Area that triggers an event

    JCheckBox Area either selected / not selected

    JComboBox Drop down list for selection

    JList A list where user can make selectionJPanel Container where components can be

    placed

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    7/32

    Swing Overview

    Classes that are used to create GUI components are

    part of GUI components from packagejavax.swing The original GUI components fromAbstract

    Windowing Toolkitpackage java.awt

    Fig 12.3 (below) show common superclasses of many

    Swing componentsjava.lang.Object

    java.awt.Component

    java.awt.Container

    javax.swing.JComponent

    Fig 12.3

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    8/32

    JLabel

    Labels:

    provide text instructions or information on a GUI. display a single line or read-onlytext

    Following are Label constructors and methods.

    public class LabelTest extends JFrame {

    private JLabel label1, label2, label3;

    // JLabel constructor with a string argument

    label1 = new JLabel( "Label with text" );

    label1.setToolTipText( "This is label1" );

    c.add( label1 );

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    9/32

    // JLabel constructor with string, Icon and alignment arguments

    Icon bug = new ImageIcon( "bug1.gif" );label2 = new JLabel( "Label with text and icon",

    bug, SwingConstants.LEFT );

    label2.setToolTipText( "This is label2" );

    c.add( label2 );

    javax.Swing support two image formats: GIF and

    JPEG/JPG SwingConstants.CENTER, SwingConstants.BOTTOM

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    10/32

    // JLabel constructor no arguments

    label3 = new JLabel();label3.setText( "Label with icon and text at bottom" );

    label3.setIcon( bug );

    label3.setHorizontalTextPosition( SwingConstants.CENTER );

    label3.setVerticalTextPosition( SwingConstants.BOTTOM );

    label3.setToolTipText( "This is label3" );

    c.add( label3 );

    the statement indicate that the text will be centered

    horizontally and will appear at the bottom of the label. Thus

    icon will appear above the text

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    11/32

    JTextFields & JPasswordField

    JTextFields is single-line areas in which text can be

    entered by user from the keyboard JPasswordFields (packagejavax.swing) show that the

    character was typed as the user enters characters, but

    hides the characters (e.g., ***). When user press Enterkey inJTextFieldor

    JPasswordFieldthe action event occurs

    // Fig. 12.7: TextFieldTest.javaimport java.awt.*;

    import java.awt.event.*;

    importjavax.swing.*;

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    12/32

    TextFieldTest.java

    public class TextFieldTest extends JFrame {

    private JTextField text1, text2, text3;

    private JPasswordField password;

    public TextFieldTest() {

    ...

    // construct textfield with default sizingtext1 = new JTextField( 10 ); // 10 columns

    c.add( text1 );

    // construct textfield with default text

    text2 = new JTextField( "Enter text here" ); // size as textc.add( text2 );

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    13/32

    TextFieldTest.java

    // construct textfield with default text and

    // 20 visible elements and no event handler

    text3 = new JTextField( "Uneditable text field", 20 );

    text3.setEditable( false );

    c.add( text3 );

    // construct textfield with default textpassword = new JPasswordField( "Hidden text" );

    c.add( password );

    // TextFieldHandleris inner class for event handling

    TextFieldHandler handler = new TextFieldHandler();

    text1.addActionListener( handler ); // as for text2 & text3

    password.addActionListener( handler );

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    14/32

    TextFieldTest.java

    // inner class for event handling

    private class TextFieldHandlerimplements ActionListener {public void actionPerformed( ActionEvent e ) {

    String s = "";

    if ( e.getSource() == text1 ) // as for text2, & text3

    s = "text1: " + e.getActionCommand(); // from keyboardelse if ( e.getSource() == password ) {

    JPasswordField pwd = (JPasswordField) e.getSource();

    s = "password: " + new String( pwd.getPassword() );

    } // else if

    JOptionPane.showMessageDialog( null, s );

    } //actionPerformed

    } // TextFieldhandler

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    15/32

    JButton

    AButton is a component that the user click to trigger a

    specific action. Several types of buttons: command buttons,

    checkboxes, toggle (on/off) buttons and radio buttons

    A command button generates a button event when theuser clicks the button with the mouse.

    Fig 12.10 ButtonTest.java program example of creating

    buttons

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    16/32

    Example: ButtonTest.java

    import java.awt.*;

    import java.awt.event.*;import javax.swing.*;

    public class ButtonTest extends JFrame {

    // declaration

    private JButton ButtonOK, ButtonCancel;

    // ButtonTest constructor

    public ButtonTest() {super( "Testing Buttons" );

    Container c = getContentPane();

    c.setLayout( new FlowLayout() );

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    17/32

    ButtonTest.java

    // create buttons

    ButtonOK = new JButton( "OK" );c.add( ButtonOK ); // put button on container

    ButtonCancel = new JButton( "Cancel" );

    c.add( ButtonCancel );

    setSize( 275, 100 );// size of windowshow();// show window on screen

    } // ButtonTest constructor

    public static void main( String args[] ) {ButtonTest app = new ButtonTest();

    } // main

    } //ButtonTest class

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    18/32

    JCheckbox and JRadioButton

    The Swing GUI component contain 3 types of state

    button JToggleButton,

    JCheckBox and

    JRadioButton They have on/off or true/false values

    Class JCheckBox & JRadioButton are subclasses of

    JToggleButton

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    19/32

    Example: CheckBoxTest.java

    public class CheckBoxTest extends JFrame {

    private JTextField t; // declarationprivate JCheckBox bold, italic;

    public CheckBoxTest() {t = new JTextField( Lihat font berubah", 20 );t.setFont( new Font( "TimesRoman", Font.PLAIN, 14 ) );

    c.add( t );

    // create checkbox objects & labelBoldbold = new JCheckBox( "Bold" );c.add( bold ); // add object to Container c

    italic = new JCheckBox( "Italic" );c.add( italic );

    / /CheckBoxTest constructor

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    20/32

    CheckBoxTest.java

    private class CheckBoxHandler implements ItemListener {

    private int valBold = Font.PLAIN;// declaration with default value

    private int valItalic = Font.PLAIN;

    public void itemStateChanged( ItemEvent e ) {

    if ( e.getSource() == bold )

    if ( e.getStateChange() == ItemEvent.SELECTED )

    valBold = Font.BOLD;else

    valBold = Font.PLAIN;

    if ( e.getSource() == italic )

    if ( e.getStateChange() == ItemEvent.SELECTED )

    valItalic = Font.ITALIC;

    else

    valItalic = Font.PLAIN;

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    21/32

    CheckBoxTest.java

    // set current font after ItemEvent.SELECTED

    t.setFont( new Font( "TimesRoman", valBold + valItalic, 14 ) );

    t.repaint();

    } // itemStateChanged

    } // CheckBoxHandler

    } //CheckBox class

    JRadioButton : exercise.

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    22/32

    JComboBox (Choice Buttons)

    A combo box sometimes called a drop-down listprovides a list

    of item from which the user can make selection.

    Combo box implemented using class JComboBox

    icons[1] contain a2.gif

    // Fig 12.13 ComboBoxTest.java

    public class ComboBoxTest extends JFrame {

    private JComboBox images; // declaration

    private JLabel label;private String names[] = { a1.gif", a2.gif" };

    private Icon icons[] =

    { new ImageIcon( names[ 0 ] ),

    new ImageIcon( names[ 1 ] ), };

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    23/32

    Example: ComboBoxTest.java

    public ComboBoxTest() {//constructor

    // create JComboBoxobject using the Strings in array namesimages = new JComboBox( names );

    images.setMaximumRowCount( 3 );// no. of element displayed

    // inner class that implement ItemListener

    images.addItemListener( new ItemListener() {

    // listen to state chage

    public void itemStateChanged( ItemEvent e ) {

    // get image index and set label for icon

    label.setIcon( icons[ images.getSelectedIndex() ] );

    } } );

    c.add( images ); // add image to Container

    }

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    24/32

    JList

    A list display a series of items from which the user may select

    one or more items. List are created with class JList

    class JList supportsingle-selection list andmultiple-selection

    lists

    // Fig 12..14 ListTest.java

    public class ListTest extends JFrame {

    private JList colorList;// declaration

    private Container c;

    private String colorNames[] = { "Black", "Blue, ...};

    private Color colors[] = { Color.black, Color.blue, ...};

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    25/32

    Example: ListTest.java

    public ListTest() { // constructor

    // create a list with the items in the colorNames array

    colorList = new JList( colorNames );

    colorList.setVisibleRowCount( 4 );// 4 items visible in list

    // do not allow multiple selectionscolorList.setSelectionMode(

    ListSelectionModel.SINGLE_SELECTION );

    // add a JScrollPane containing the JList to the content panec.add( new JScrollPane( colorList ) );

    } // ListTest Constructor

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    26/32

    Multiple-Selection Lists

    A multiple-selection list enables the user to selectmany item

    from the JList by clicking once on each desired item.

    A SINGLE_INTERVAL_SELECTION

    Allow selection contiguous range of items

    clicking the first item, then holding Shift key while clicking

    the last item A MULTIPLE_INTERVAL_SELECTION

    Allow continuous item to be select by holding Ctrl key while

    clicking the item

    To de-select an item, hold the Ctrl key while clicking an item asecond time (at first list)

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    27/32

    Example: MultipleSelection.java

    public class MultipleSelection extends JFrame {

    private JList colorList, copyList;

    private JButton copy;

    public MultipleSelection() {

    colorList = new JList( colorNames ); // instantiate

    colorList.setVisibleRowCount( 5 ); //no. of visible itemscolorList.setFixedCellHeight( 15 ); //height of pixel

    colorList.setSelectionMode(

    ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );

    c.add( new JScrollPane( colorList ) );

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    28/32

    28

    What is Interface?

    In many ways, Interface is very similar to abstract class but it marks with

    interface keyword instead ofabstract classkeyword.

    public interface InterfaceName {

    }

    Unlike abstract class which can also contain nonabstract methods, interfacecontain ONLYabstract methods and constants.

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    29/32

    29

    How to define interface? Defining an interface:

    interface InterfaceName{

    /* Constant declarations *//* Method signatures */

    } E.g:

    public interface Moveable{

    final int MAX_MOVE = 20;final int MIN_MOVE = 1;public void move();

    }

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    30/32

    30

    Differences between interface and abstractclass (1)

    Like abstract class,

    1. if a class implement an interface, you have to override

    the interfaces methods in the class.

    2. You cannot create instances from an interface by usingnew operator.

    3. Interface can be a type as well.

    Runnable r;4. the purpose of creating interface is because of

    polymorphism.

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    31/32

    31

    Differences between interface and abstractclass (2)

    Unlike abstract class,

    1. You can have multiple interface in one class. To implement thoseinterfaces, use implementskeyword and separate interfaces by

    comma.

    public class Test implements Runnable,

    ActionListener, MouseMotionListener {

    /* Overridden interfaces methods */

    }

    2. Interface uses interface keyword.

    3. Interface is NOT designed to be superclass. Interface is designed

    to add some behaviors to a class.

  • 7/30/2019 Chapter 2.1 Basic GUI Components

    32/32

    32

    Different between interface and abstract

    class (3)4. In the relationships, we say that:

    4.1. A relationship between class/abstract class and classis a strong

    relationship. It is known as IS-A relationship.

    E.g:A duck is a bird. It clearly means the duck is really a bird. So the

    bird can be a superclass of a duck. It could be either concrete or

    abstract class.

    4.2. A relationship between class and interfaceis a weak

    relationship. It is known as Is-kind-ofrelationship.

    E.g:Aduck is flyable.

    Flyable can never ever be the superclass of theduck. It just means this duck can fly. So flyable is interface.


Recommended