Creating GUI with Swing.pdf

Embed Size (px)

Citation preview

  • 7/29/2019 Creating GUI with Swing.pdf

    1/34

    All rights reserved. Reproduction and/or distribution in whole or inpart in electronic, paper or other forms without written permission

    is prohibited.

    Java ReferencePoint SuiteSkillSoft Corporation. (c) 2002. Copying Prohibited.

    Reprinted for Balaji Nallathambi, [email protected]

    Reprinted with permission as a subscription benefit of Books24x7,http://www.books24x7.com/

    http://www.books24x7.com/http://www.books24x7.com/
  • 7/29/2019 Creating GUI with Swing.pdf

    2/34

    Table of ContentsPoint 5: Creating GUI with Swing....................................................................................................1

    Swing Programming.........................................................................................................................2Swing Components.................................................................................................................2Using Swing Packages...........................................................................................................2

    Basic Swing Programming..............................................................................................................4Adding a Tool Tip and an Image Icon to a Button...................................................................4Adding Borders to Swing Components...................................................................................5Creating a Text Area Containing a Scroll Bar.........................................................................8Creating a Password Field......................................................................................................9Creating a List Box Control...................................................................................................10Creating a Combo Box Component......................................................................................13Creating a Check Box Component.......................................................................................14Creating a Toggle Button......................................................................................................16Creating a Radio Button........................................................................................................16Creating a Slider Bar.............................................................................................................17

    Advanced Swing Programming.....................................................................................................19

    Layout Managers..................................................................................................................19Creating a Tabbed Pane.......................................................................................................22Creating Menus and Sub Menus..........................................................................................24Creating a Tree Component.................................................................................................25Creating a Table Component................................................................................................28UserValidation Feature.......................................................................................................29

    Using Threads in a Swing Application.........................................................................................31

    i

  • 7/29/2019 Creating GUI with Swing.pdf

    3/34

    Point 5: Creating GUI with SwingDeepak PandyaJava" Foundation Class (JFC) is a development kit that simplifies the task of creating components,such as menus, labels, and buttons. You use JFC components to create graphicbased applets andapplications. The Swing package is part of JFC and is integrated into version 1.2 of Java.

    This ReferencePoint introduces you to the fundamentals of creating Graphical User Interface (GUI)applications by using Swing components, such as trees, tabbed panes, images, and tool tips. Thesecomponents are flexible and have varied features. For example, you can create a button in variousshapes for an applet, add an icon or image to the button, or change the border of the button.

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

    http://www.books24x7.com//viewer.asp?bookid=4128&chunkid=478205610?bkid=4128&destid=8362#8362
  • 7/29/2019 Creating GUI with Swing.pdf

    4/34

    Swing ProgrammingTo use Swing components, include the javax.swing package in the Java program. This packageprovides a set of classes to manage user interface components such as trees and panes. Allclasses in the javax.swing package are derived from the JComponent class, which in turn, isderived from the java.awt.Container class. All these classes are container classes.

    The hierarchy of swing classes is shown in Figure 251. A container class has a pane that is usedas a container for all components. You can access this pane by using the getContentPane()method. Every Swing program contains at least one toplevel Swing container, such as JWindow,JFrame, JPane, and JApplet. The toplevel Swing container provides support for the Swingcomponents.

    Figure 251: Class Hierarchy in SwingSwing Components

    The most commonly used Swing components are:

    JFrame: A toplevel container for all Swing components such as labels and buttons.

    JPanel: A container that enables you to position the Swing components.

    JButton and JLabel: Components that are selfsufficient entities inside a container.

    Note The Swing components are JavaBeans and can be used in other applications in variousenvironments.

    Using Swing Packages

    You use swing packages to create Swing components. Table 251 describes the various Swing

    packages:

    Table 251: The Swing Packages

    Swing Packages Description

    Javax.swing.border Enables you to create borders around components.

    Javax.swing.colorchooser Enables you to display a color chart and choose a color.

    Javax.swing.event Enables you to manage events in eventdriven programming.

    Javax.swing.filechooser Enables you to provide File selection dialog boxes in an application.

    Javax.swing.plaf Provides Pluggable Look and Feel (PLAF) capability.

    Javax.swing.table Enables you to display and manipulate the data in a table.

    Javax.swing.text

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    5/34

    Enables you to create and manipulate singleline or multiple linetextentry fields.

    Javax.swing.html Allows you to display Swing applications in the HTML format.

    Javax.swing.tree Allows you to create and manipulate a tree view of data.

    Java ReferencePoint Suite 3

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    6/34

    Basic Swing ProgrammingListing 251 shows how to create a frame by using Swing programming:

    Listing 251: A Swing Program

    import javax.swing.*;public class Hello

    {public static void main(String[] args){

    JFrame frame=new JFrame ("SwingProgram");JLabel label=new JLabel ("I swing ");frame.getContentPane().add(label);frame.setVisible(true);

    }}

    This code imports the main swing package by using the statement:

    import javax.swing.*.

    The execution of the program starts from the main() method. An object of the JFrame class isdeclared by passing the title of the frame, SwingProgram, as its parameter. An object of the JLabelclass is declared with the caption, I swing. The frame container uses the ContentPane objectobtained using the getContentPane()method. The add() method enables you to add components tothe ContentPane object.

    The output of the code is shown in Figure 252:

    Figure 252: Frame Created Using SwingAdding a Tool Tip and an Image Icon to a Button

    You can use tool tips and images to make a program interactive and easy to understand.

    Tool tips are short descriptive messages that appear when you position the mouse pointer over aparticular region of an application. You can add a tool tip by using the setToolTip() method of theJComponent class and retrieve the tool tip by using the getToolTipText() method. The Tool Tipmanager enables you to customize the appearance of a tool tip. To access the Tool Tip manager,use the sharedInstance() method.

    In order to convey the purpose of a component, you can use the image icon. For example, youmight use a printer icon for the print button of an application.

    Use the ImageIcon class to include images in your application. The Icon interface contains thedefinition of the methods implemented in the ImageIcon class.

    Listing 252 illustrates the code to add an image icon and a tool tip to a button:

    Listing 252: Adding an Image Icon and a Tool Tip

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

    public class Imageex extends JApplet{

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    7/34

    JLabel image;public void init(){JPanel p=new JPanel ();getContentPane().add(p);

    /* The ImageIcon constructor takes the name of animage file as its parameter.*/

    Icon abc=new ImageIcon ("Img14.gif");

    // The label acts as a placeholder for the iconimage=new JLabel(abc);

    image.setToolTipText("Tool Tip Example for you");p.add(image);

    }}

    In this example, the ImageIcon constructor uses the name of an image file as its parameter.Passing the ImageIcon object to the JLabel constructor creates the label and image. Use thesetToolTipText() method to set a tool tip for the label and the add() method to add the label to thepanel. The output of the code is shown in Figure 253:

    Figure 253: Applet Showing a Label with an Image and a Tool TipAdding Borders to Swing Components

    The Swing package enables you to change the appearance of a component using different borders.For example, you can add an etched border or a bevel border to a button or a label.

    Use the BorderFactory class of the javax.swing.border package to apply borders to a component.

    The Border interface has methods to draw borders around the component. Use the setBorder()method to add borders to the components and the getBorder() method to determine the borders ofthe components.

    The various types of border implementers are:

    Bevel border: Enables you to draw simple threedimensional (3D) borders aroundcomponents. You can draw different colored lines to show depth. There are two types ofBevel borders raised and lowered.

    Compound border: Enables you to create a border by combining two borders, with oneborder nested inside the other.

    Java ReferencePoint Suite 5

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    8/34

    Empty border: Occupies the space within the container to add space around thecomponents.

    Note Empty borders have replaced Insets from the AWT package. AWT is a package that containsan integrated set of classes to manage user interface components. JFC is an extension of

    AWT.

    Matte border: Occupies space around components and enables you to add colors or imageicons to the matte borders.

    Line border : Creates an ordinary line around components. The color class that you use todraw colored lines is a part of the java.awt package. To apply this type of border, importthree packages: java.awt, javax.swing, and javax.swing.border.

    Etched border: Provides an etched border that shows depth. You can create an etchedborder by using the createEtchedBorder() method.

    Titled border: Enables you to display a text string on the borders around components.

    Listing 253 contains the code to create a raised bevel border:

    Listing 253: Creating a Raised Bevel Border

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

    import java.applet.*;

    public class Bevelborder extends JApplet

    {public void init()

    {JPanel p=new JPanel();getContentPane().add(p);JButton mybutton=new JButton("A Bevel Border Example");Border bevelborder=BorderFactory.createBevelBorder(BevelBorder.RAISED);mybutton.setBorder(bevelborder);p.add(mybutton);}}

    In this example, the mybutton object of the JButton class is created and assigned the caption, ABevel Border Example. You use the createBevelBorder() method of the BorderFactory to create thebevel border, the setBorder() method to set the border around the button. The add() method is usedto add a button to the panel.

    The output of the code is shown in Figure 254:

    Java ReferencePoint Suite 6

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    9/34

    Figure 254: Applet Showing a Raised Bevel BorderTo apply a lowered bevel border, replace the word RAISED in Listing 253 with LOWERED.

    The output is shown in Figure 255:

    Figure 255: Applet Showing a Lowered Bevel BorderListing 254 contains the code to create a line border:

    Listing 254: Creating a Line Border

    import javax.swing.*;import javax.swing.border.*;import java.awt.*;import java.applet.*;public class Lineborder extends JApplet{

    public void init(){

    JPanel p=new JPanel();getContentPane().add(p);JButton mybutton=new JButton("A Line Border Example");Borderlineborder=BorderFactory.createLineBorder();mybutton.setBorder(lineborder);

    p.add(mybutton);}

    }

    You use the createLineBorder() method of the BorderFactory class to create a bevel border and thesetBorder() method to set the border around the button.

    The output of the code is as shown in Figure 256:

    Java ReferencePoint Suite 7

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    10/34

    Figure 256: Applet Showing a Line BorderListing 255 contains the code to create an etched border:

    Listing 255: Creating an Etched Border

    import javax.swing.*;import javax.swing.border.*;import java.awt.*;import java.applet.*;public class Etchedborder extends JApplet{

    public void init(){

    JPanel p=new JPanel();getContentPane().add(p);JButton mybutton=new JButton("An etched Border Example");Border etchedborder=BorderFactory.createEtchedBorder();mybutton.setBorder(etchedborder);p.add(mybutton);

    }}

    You use the createEtchedBorder() method of the BorderFactory class to create an etched borderand the setBorder() method to set the border around the button.

    The output of the code is shown in Figure 257:

    Figure 257: Applet Showing an Etched BorderCreating a Text Area Containing a Scroll Bar

    Text areas are similar to text fields. However, a text area allows you to enter multiple lines, while atext field allows you to enter only a single line. You can specify the dimensions for a text area. Forexample, the code, JTextBox(5,15)creates a text area with 5 rows and 15 columns of visible text.You use scroll bars to view the remaining text.

    Listing 256 contains the code to create a text area component:

    Listing 256: Creating a Text Area with a Scroll Bar

    import javax.swing.*;import java.awt.*;import java.applet.*;public class Scrollit extends JApplet

    Java ReferencePoint Suite 8

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    11/34

    {

    public void init(){JPanel p=new JPanel();JTextArea ta;

    ta=new JTextArea(5,15);

    JScrollPane pane=new JScrollPane(ta);

    getContentPane().add(p);p.add(pane);

    }}

    In this example, the scrollpane is created using the JScrollPane class. You add the text areacomponent to the scroll pane that contains horizontal and vertical scroll bars. Use the add() methodto add the scroll pane to the panel.

    The output of the code is shown in Figure 258:

    Figure 258: Text Area Component with Scroll BarsCreating a Password Field

    Use the JPasswordField class to create a password field. You can use any character as an echocharacter for the password field. An echo character appears in the password field in place of theactual text that you type. The default echo character is an asterisk (*).

    Listing 257 contains the code to create a password field.

    Listing 257: Creating a Password Field

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

    import java.applet.*;public class Password extends JApplet{

    public void init(){JPanel p=new JPanel();JLabel label1=new JLabel("Default Password Field");JLabel label2=new JLabel("Echo set Password Field");JPasswordField pw1=new JPasswordField(10);JPasswordField pw2=new JPasswordField(10);pw2.setEchoChar('?');getContentPane().add(p);p.add(label1);p.add(pw1);p.add(label2);p.add(pw2);

    Java ReferencePoint Suite 9

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    12/34

    }}

    In this code, you use the JPasswordField class to create two password fields. The first passwordfield has an asterisk (*) as the default echo character. Use the setEchoChar() method in the code to

    set a question mark (?) as the echo character for the second password field.The output of the code is shown in Figure 259:

    Figure 259: Applet Showing the Password FieldCreating a List Box Control

    A list box enables you to view a list of items. You use the JList class to create the list box control.

    The methods of the JList class are:

    setSelectionMode(): Is used for single or multiple selection. The parameters for this methodare:

    SINGLE_SELECTION for selecting only single items. Index 0. For example,SetSelectionMode(0)allows you to select only single item from the list.

    SINGLE_INTERVAL_SELECTION for selecting a continuos list of items.

    MULTIPLE_INTERVAL_SELECTION for selecting multiple items in any order.

    The default parameter is multiple interval selection.

    setVisibleRowCount(int count): Enables you to specify the number of elements that shouldbe visible in the list. For example, the setVisibleRowCount(4) method lists four items. Youcan use the scroll bars to see the remaining items.

    getSelectedValue(): Returns the value of the selected item. If you do not select any item, thismethod returns a null value. If you select multiple items, the method returns the value of thefirst selected item.

    getSelectedIndex(): Returns the index of the selected item.

    getSelectedValues(): Returns an array of selected values.

    Java ReferencePoint Suite 10

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    13/34

    Listing 258 contains the code to create a list box:

    Listing 258: Creating a List Box

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

    import java.applet.*;

    public class Listbox extends JApplet{

    // Declaring variablesJPanel p;JLabel label1;JList list1;JButton press;

    public void init(){

    //Initialize the variablesp=new JPanel();label1=new JLabel("Shopping Cart Items");

    String itemlist [] = {"Books","Chocolates","Trousers","Jewelry","Toys","Garments"};

    list1=new JList(itemlist);

    /* Selection mode 0 is to select only oneitem from the list */

    list1.setSelectionMode(0);

    press=new JButton("BUY");

    getContentPane().add(p);

    p.add(label1);p.add(list1);p.add(press);

    }}

    In this example, the itemlist variable of the String datatype contains all the required items for a list.This variable is passed as a parameter to the JList class by using the statement list1=newJList(itemlist). Use the add() method to add list boxes, labels, and buttons to the panel. You canselect only a single item because the selection mode is set to 0.

    The output of the code sample is shown in Figure 2510:

    Java ReferencePoint Suite 11

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    14/34

    Figure 2510: Applet Showing a List Box for Single SelectionSet the selection mode to 1 to select multiple items in continuous order.

    The output for this selection mode is shown in Figure 2511:

    Figure 2511: Applet Showing a List Box for Continuous Multiple SelectionSet the selection mode to 2, if you want to select multiple items in any order in the list.

    The output for this selection mode is shown in Figure 2512:

    Java ReferencePoint Suite 12

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    15/34

    Figure 2512: Applet Showing a List Box for Multiple Selection in Any OrderCreating a Combo Box Component

    A combo box resembles a dropdown menu and allows you to select only single items from a list.

    You can create a combo box by using the JComboBox class. A combo box provides a text field inwhich you can enter an item of your choice. To do this, specify true as a parameter for thesetEditable() method. Use the getSelectedItem() method to retrieve selected items.

    Note By default, the setEditable() method is assigned a false value.

    Listing 259 illustrates the code to create a combo box:

    Listing 259: Creating a Combo Box

    import javax.swing.*;

    import java.awt.*;import java.applet.*;

    public class Combo extends JApplet{

    // Declaring variablesJPanel p;JLabel name;JLabel dest;JComboBox combo1,combo2;JButton press;

    public void init()

    {//Initialize the variables

    p=new JPanel();name=new JLabel("FLIGHT");dest=new JLabel("DESTINATION");

    String first[] = { "AIR INDIA","AIR EMIRATES","US AIRWAYS","BRITISHAIRWAYS","SWISS AIR"

    };combo1=new JComboBox(first);

    String second[]= { "New York","London","Mumbai","Paris","Berlin"

    };

    combo2=new JComboBox(second);

    Java ReferencePoint Suite 13

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    16/34

    press=new JButton("submit");

    getContentPane().add(p);p.add(name);p.add(combo1);p.add(dest);p.add(combo2);p.add(press);

    }}

    In this code, two objects of the JComboBox class, combo1 and combo2, are created. Two variables,first and second, of the String datatype contain all the items for the combo box. The names of thesevariables are passed as a parameter to the JComboBox class.

    The output of the code is shown in Figure 2513:

    Figure 2513: Applet Showing a Combo BoxMake the following change in Listing 259 combo1.setEditable(true);

    for an editable combo box, as shown in Figure 2514:

    Figure 2514: Applet Showing an Editable Combo BoxCreating a Check Box Component

    Use the JCheckBox class to create a check box. You can create a selected check box by passing atrue parameter to the setSelected() method.

    The constructors of the JCheckBox class are:

    JCheckBox(Icon i): Provides an icon for the checkbox

    Java ReferencePoint Suite 14

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    17/34

    JCheckBox(Icon i, Boolean state): Provides an icon for the checkbox and sets a booleanvalue for the check box

    JCheckBox(String s): Provides a string that appears along with the check box

    JCheckBox(String s, Boolean state): Provides a string and a boolean value for the checkbox

    Listing 2510 contains the code to create a check box:

    Listing 2510: Creating a Check Box

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

    public class Selectbox extends JApplet

    {JPanel p;

    JFrame frame=new JFrame();JLabel name;JLabel Qual;JTextField tname,tqual;JCheckBox selection1,selection2;JButton press;

    public void init()

    {p=new JPanel();name=new JLabel("NAME");Qual=new JLabel("QUALIFICATION");tname=new JTextField(5);tqual=new JTextField(5);selection1=new JCheckBox("Driving License");

    selection2=new JCheckBox("Passport");

    selection1.setSelected(true);

    press=new JButton("submit");

    getContentPane().add(p);p.add(name);p.add(tname);p.add(Qual);p.add(tqual);p.add(selection1);p.add(selection2);p.add(press);

    }

    }

    In this code, two check boxes are created using the JCheckBox class. Use the add() method to addthese check boxes to the panel.

    The output of the code is shown in Figure 2515:

    Java ReferencePoint Suite 15

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    18/34

    Figure 2515: Applet Showing a Check BoxCreating a Toggle Button

    A toggle button is a twostate button with active and inactive states. For example, the cut and copybuttons of an application are activated only when select some text in the application. You use theJToggleButton class to create toggle buttons.

    Listing 2511 contains the code to create a toggle button:

    Listing 2511: Creating a Toggle Button

    import javax.swing.*;import java.applet.*;public class Toggle extends JApplet{

    public void init(){

    JPanel p=new JPanel();JToggleButton tb=new JToggleButton("Toggle Button");getContentPane().add(p);p.add(tb);

    }

    }

    You use the JToggleButton class to create a toggle button and add the button to the panel by usingthe add() method.

    The output of the code is shown in Figure 2516:

    Figure 2516: Applet Showing a Toggle ButtonCreating a Radio Button

    You use radio buttons to provide a set of options in an application. Radio buttons allow a mutuallyexclusive selection. An example is the male or female option in a the admission form of a university.The buttons created for a particular choice should be placed under one group. To create a buttongroup, use the JButtonGroup class.

    Listing 2512 contains the code to create a radio button.

    Listing 2512: Creating a Radio Button

    Java ReferencePoint Suite 16

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    19/34

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

    public class Radio extends JApplet{

    public void init(){JPanel p=new JPanel();JLabel status=new JLabel("Candidate Profile");JLabel gender=new JLabel("Gender");JButtonGroup bg1=new JButtonGroup();JButtonGroup bg2=new JButtonGroup();JRadioButton option1= new JRadioButton ("Married",true);JRadioButton option2= new JRadioButton ("Single");JRadioButton option3= new JRadioButton ("Male");JRadioButton option4= new JRadioButton ("Female");

    bg1.add(option1);bg1.add(option2);bg2.add(option3);bg2.add(option4);

    getContentPane().add(p);

    p.add(status);

    p.add(option1);p.add(option2);p.add(gender);p.add(option3);p.add(option4);

    }}

    The object of the JRadioButton class is created. Two groups for radio buttons, Candidate Profileand Gender, are created using the JButtonGroup class. Use the add() method to add the radiobuttons to the button group.

    The output of the code is shown in Figure 2517:

    Figure 2517: Applet Showing a Radio ButtonCreating a Slider Bar

    Sliders allow you to select a numerical value from a range of values. For example, you can selectyour height from a given range of values on a slider bar. You use the JSlider class to add sliders toan application.

    Listing 2513 contains the code to add sliders on an application:

    Listing 2513: Creating a Slider

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

    Java ReferencePoint Suite 17

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    20/34

    import java.applet.*;

    public class Slider extends JApplet{public void init(){JPanel p=new JPanel();JButton b1=new JButton("Select your weight in Pounds");JButton b2=new JButton("Select your height in Feet");JSlider h,v ;

    //Slider to show values 0 to 200 with tickspacing 20v=new JSlider(JSlider.VERTICAL,1,10,6);v.setMajorTickSpacing(20);v.setPaintLabels(true);

    //Slider to show values 0 to 100 with tickspacing 10h=new JSlider(JSlider.HORIZONTAL,0,150,20);h.setMajorTickSpacing(10);h.setPaintLabels(true);getContentPane().add(p);p.add(b2);p.add(v);p.add(h,BorderLayout.SOUTH);p.add(b1);

    }}

    Use the setMajorTickSpacing() method to show values at intervals of 1 units each. ThesetPaintLabels()method is passed as a true parameter to display the label of the values.

    The output of the code is shown in Figure 2518:

    Figure 2518: Applet Showing an Example of Creating Sliders

    Java ReferencePoint Suite 18

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    21/34

    Advanced Swing ProgrammingYou can create applets by advanced swing programming using layout managers, creating menus,trees and table components, and providing user validation feature.

    Layout Managers

    Layout managers are objects that determine how components are located in the container of anapplication. Layout managers determine the size and position of the components.

    The various types of layout managers are:

    Flow Layout Manager: Positions the components one after the other. The components areplaced on the next line when the layout manager reaches the border of the container. Forexample, the five buttons with label B1 when placed with a flow layout appear as shown inFigure 2519:

    Figure 2519: Flow Layout

    Grid Layout Manager: Enables you to arrange and display components in a rectangular grid.This layout manager also displays components in a grid of cells, as shown in Figure 2520:

    Figure 2520: Grid Layout

    Border Layout Manager: Enables you to position the components along the major directions:North, South, East, West and Center as shown in Figure 2521:

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    22/34

    Figure 2521: Border Layout

    Gridbag Layout Manager: Helps customize controls. For example, you can resize the buttonor place components in specified rows and columns. First, set the layout variables in aGridBagConstraints object. This object determines the constraints such as grid and weight ofeach component in a layout. Then, associate the constraint with the component by using thesetConstraints() method. This method takes two parameters, the JClass object and theGridBagConstraints object. Use the gridx and gridy attributes to specify the row and columnfor the component to be displayed.

    Listing 2514 contains the code to create a gridbag layout:

    Listing 2514: Creating a Gridbag Layout

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

    public class Gridbag extends JApplet

    { JPanel p;JLabel no;JLabel fn;JLabel ln;

    JLabel add;JLabel phone;JTextField tno;JTextField tfn;JTextField tln;JTextField tadd;JTextField tphone;JButton accept;

    GridBagLayout g1;GridBagConstraints gbc;

    public void init(){

    p=new JPanel();getContentPane().add(p);

    g1=new GridBagLayout();p.setLayout(g1);gbc=new GridBagConstraints();

    no=new JLabel("ORDER NO");fn=new JLabel("FIRST NAME");ln=new JLabel("LAST NAME");add=new JLabel("ADDRESS");phone=new JLabel("PHONE");tno=new JTextField(5);tfn=new JTextField(5);tln=new JTextField(5);tadd=new JTextField(5);tphone=new JTextField(5);accept=new JButton("ACCEPT");

    Java ReferencePoint Suite 20

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    23/34

    gbc.anchor=GridBagConstraints.NORTHWEST;gbc.gridx=1;gbc.gridy=1;g1.setConstraints(no,gbc);p.add(no);

    gbc.anchor=GridBagConstraints.NORTHWEST;

    gbc.gridx=10;

    gbc.gridy=1;

    g1.setConstraints(tno,gbc);p.add(tno);

    gbc.anchor=GridBagConstraints.NORTHWEST;

    gbc.gridx=1;gbc.gridy=5;

    g1.setConstraints(fn,gbc);p.add(fn);

    gbc.anchor=GridBagConstraints.NORTHWEST;

    gbc.gridx=10;

    gbc.gridy=5;g1.setConstraints(tfn,gbc);p.add(tfn);

    gbc.anchor=GridBagConstraints.NORTHWEST;gbc.gridx=1;gbc.gridy=10;

    g1.setConstraints(ln,gbc);p.add(ln);

    gbc.anchor=GridBagConstraints.NORTHWEST;gbc.gridx=10;gbc.gridy=10;

    g1.setConstraints(tln,gbc);

    p.add(tln);

    gbc.anchor=GridBagConstraints.NORTHWEST;gbc.gridx=1;gbc.gridy=15;g1.setConstraints(add,gbc);p.add(add);

    gbc.anchor=GridBagConstraints.NORTHWEST;gbc.gridx=10;gbc.gridy=15;g1.setConstraints(tadd,gbc);p.add(tadd);

    gbc.anchor=GridBagConstraints.NORTHWEST;gbc.gridx=1;

    gbc.gridy=20;g1.setConstraints(phone,gbc);p.add(phone);

    gbc.anchor=GridBagConstraints.NORTHWEST;gbc.gridx=10;gbc.gridy=20;g1.setConstraints(tphone,gbc);p.add(tphone);

    gbc.anchor=GridBagConstraints.SOUTHEAST;gbc.gridx=28;gbc.gridy=25;

    g1.setConstraints(accept,gbc);p.add(accept);

    }

    Java ReferencePoint Suite 21

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    24/34

    }

    The g1 and gbc variables are the variables for the layout. The setConstraints() method takes twoparameters. The gridx and gridy attributes of the GridBagConstraints method enable you to positionthe buttons, labels, and text fields.

    The output of the code is shown in Figure 2522:

    Figure 2522: An Applet with the GridBag Layout AppliedThe labels and textboxes are positioned using the gridx and gridy attributes. The leftmost columnhas position gridx=0, and the uppermost row has position gridy=0. This is similar to the X and Ycoordinates of a simple graph.

    Creating a Tabbed Pane

    Tabbed panes enable you to switch between multiple pages of an application by clicking a tab witha given label. Use the JTabbedPane class to create tabs in an application and the addTab() methodto add tabs to the tab pane.

    Listing 2515 contains the code to create a tabbed pane:

    Listing 2515: Creating a Tabbed Pane

    import javax.swing.*;

    public class Tabs extends JApplet{ public void init()

    {JTabbedPane mytab=new JTabbedPane();mytab.addTab("Administrator",new admin());mytab.addTab("Instructor",new instructor());mytab.addTab("Student",new student());getContentPane().add(mytab);}}

    class admin extends JPanel

    {JButton b1,b2;JTextField t1;

    Java ReferencePoint Suite 22

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    25/34

    public admin(){ b1=new JButton("Admin Login");t1=new JTextField(10);b2=new JButton("Click");add(b1);add(t1);add(b2);

    }}

    class instructor extends JPanel

    {JButton b1,b2;JTextField t1;

    public instructor(){ b1=new JButton("Instructor Login");t1=new JTextField(10);b2=new JButton("Click");add(b1);add(t1);add(b2);

    }}

    class student extends JPanel

    {JButton b1,b2;JTextField t1;

    public student(){ b1=new JButton("Student Login");t1=new JTextField(10);b2=new JButton("Click");add(b1);add(t1);add(b2);

    }}

    In this example, the void init()method enables you to initialize the variables of the JTabbedPaneclass. Use the addTab()method to add tabs to the mytab object of the JTabbedPane class. TheaddTab() method takes two parameters, the tab title and the class name. Use the admin class, thestudent class, and the instructor class to initialize the variables of the JButton and JTextFieldclasses.

    The output of the code is shown in Figure 2523:

    Figure 2523: Applet Showing a Tabbed PaneSimilarly, when you select the Student tab, the student login form appears, as shown in Figure2524:

    Java ReferencePoint Suite 23

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    26/34

    Figure 2524: Tabbed Pane with Student as the Active TabCreating Menus and Sub Menus

    Before creating a menu, you need to create a menu bar by using the JMenuBar class. Add themenu bar to a frame by using the setJMenuBar()method. The frame is a container for the menu bar.Use the JMenu class to create a menu and add it to the menu bar. Next, use the JMenuItem class

    to create menu items and add them to the menu.

    Listing 2516 contains the code to create a menu and a submenu.

    Listing 2516: Creating a Menu and a Sub Menu

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

    public class Menu extends JApplet

    {public static void main(String args[])

    {JFrame myframe=new JFrame("An example of creating Menu");

    JMenuBar mybar=new JMenuBar();myframe.setJMenuBar(mybar);

    JMenu eng,doc;eng=new JMenu("Engineers");doc=new JMenu("Doctors");

    mybar.add(eng);mybar.add(doc);

    JMenuItem compu,electro,mech,physician,surgeon;compu=new JMenuItem("Computers");

    electro=new JMenuItem ("Electronics");mech=new JMenuItem ("Mechanical");physician=new JMenuItem ("Physician");surgeon=new JMenuItem ("surgeon");

    eng.add(compu);eng.add(electro);eng.add(mech);doc.add(physician);doc.add(surgeon);

    JMenu submenu=new JMenu("Status");eng.add(submenu);submenu.add("Fresher");submenu.add("Experienced");

    Java ReferencePoint Suite 24

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    27/34

    myframe.setSize(400,400);myframe.setVisible(true);}

    }

    In this example, the JFrame class is used to create a frame that is a container for the menu bar. ThesetSize() method enables you to set the size of the frame and the setVisible() method is passed asa true parameter to make the frame visible. Use the JMenuBar class to create a menu bar and thesetJMenuBar() method to add the menu bar to the frame. The JMenu class enables you to createmenus and the add() method enables you to add menu items to the menu. Create menu items usingthe JMenuItem class.

    The output of the code is shown in Figure 2525.

    Figure 2525: Applet Showing a Menu BarA sub menu is shown in Figure 2526:

    Figure 2526: Applet Showing a Sub menuCreating a Tree Component

    Trees enable you to display data in a hierarchical form. You use the JTree class to create a treecomponent. The tree component has a super node from which other nodes arise. The super node issimilar to a toplevel branch of a tree from which other branches arise. The subnodes arise fromthese nodes.

    Figure 2527 shows a diagram of a tree component:

    Java ReferencePoint Suite 25

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    28/34

    Figure 2527: A Swing Class Hierarchy

    You can provide a similar presentation in your application using the JTree class.To create a tree component, add:

    A tree object by using the JTree class.1.

    A tree node by using the DefaultMutableTreeNode interface.2.

    Subnodes by using the DefaultMutableTreeNode interface.3.

    A scroll pane by using the JScrollPane class.4.

    The tree to the scroll pane by using the add() method.5.

    The scroll pane to the panel by using the add() method.6.

    Note Use the import javax.swing.tree.* statement to include the class DefaultMutableTreeNode.

    Listing 2517 contains the code to create a tree component:

    Listing 2517: Creating a Tree Component

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

    public class Tree extends JApplet{JTree tree;

    public void init(){ // Create a super node of a treeDefaultMutableTreeNode top=new DefaultMutableTreeNode("JComponentClass");

    Java ReferencePoint Suite 26

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    29/34

    // Create nodes for the treeDefaultMutableTreeNode button

    =new DefaultMutableTreeNode("JButton");DefaultMutableTreeNode togglebutton

    =new DefaultMutableTreeNode("JToggleButton");DefaultMutableTreeNode label

    =new DefaultMutableTreeNode("JLabel");DefaultMutableTreeNode list

    =new DefaultMutableTreeNode("JList");

    // Adding nodes to the super nodetop.add(button);top.add(togglebutton);top.add(label);top.add(list);

    // Create subnodes for the treeDefaultMutableTreeNode rb

    =new DefaultMutableTreeNode("JRadioButton");DefaultMutableTreeNode cb

    =new DefaultMutableTreeNode("JCheckBox");

    // Adding subnodes to the node

    togglebutton.add(rb);togglebutton.add(cb);

    // Create a treetree=new JTree(top);

    // Use putClientProperty() method to change the style // of the tree.

    tree.putClientProperty("JTree.lineStyle","Angled");

    // Create a scroll pane and add the tree to the// the scroll pane

    JScrollPane pane=new JScrollPane(tree);JPanel p=new JPanel();getContentPane().add(p);

    // Add scroll pane to the panelp.add(pane);

    }}

    You use the JTree class to create a tree component. The DefaultMutableTreeNode() interfaceenables you to create nodes for the tree. The putClientProperty() method assigns a line style to thetree.

    The output of the code in Listing 2517 is shown in Figure 2528:

    Java ReferencePoint Suite 27

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    30/34

    Figure 2528: Applet Showing a Tree ComponentCreating a Table Component

    A table component enables you to display data in the tabular format. You use the JTable class tocreate a table and the constructor of the JTable class to add data and headings to the table. Thesyntax for the constructor is: JTable(Object data[][],Object columnheader[]).

    Listing 2518 contains the code to create a table component:

    Listing 2518: Creating a Table Component

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

    public class Table extends JApplet{public void init(){JPanel p=new JPanel();String colHead[]=

    {"S.NO","BookTitle","Author","Publisher"};String data[][]=

    {{"1","The Delicious Recipe","Susan"

    ,"New York Publishers "},{"2","Unbelievable Truth","Trim et

    al","Triger Publishers"},{"3","Love to Study","Kidy","DBS"}

    };

    JTable table=new JTable(data,colHead);JScrollPane pane=new JScrollPane(table);getContentPane().add(p);p.add(pane);

    }}

    Java ReferencePoint Suite 28

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    31/34

    You create a table using the JTable class. A String datatype array displays the content of the table.The variable colHead[] contain the column heading, and the variable data[][] contains the tablecontent.

    The output of the code is shown in Figure 2529:

    Figure 2529: Applet Showing a Table ComponentUserValidation Feature

    You can create applications that include the functionality to validate data. For example, you canvalidate the data entered in the text field of an application form and flash a message if the text fieldis blank. To create such applications, implement the ActionListener interface by using the keywordimplements. This interface contains methods that are required to manage the event. When anevent, such as a mouseclick, occurs, an ActionEvent object is generated. This object containsinformation such as a mouseclick event. Next, the getSource() method of the ActionEvent classreturns a reference to the component that triggered the event. For example, when you click Submitbutton on a form, the getSource() method returns a reference to the Submit button.

    Listing 2519 contains the code to create an application with user validation features:

    Listing 2519: Creating a User Validation Form

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

    public class Validation extends JApplet implements ActionListener{ JPanel p;

    JLabel no;JTextField tno;JButton accept;

    public void init(){

    p=new JPanel();getContentPane().add(p);no=new JLabel("ORDER NO");tno=new JTextField(5);accept=new JButton ("ACCEPT");p.add(no);p.add(tno);p.add(accept);accept.addActionListener(this);

    }

    public void actionPerformed (ActionEvent e){Object obj = e.getSource();

    if(obj == accept)

    { String no1=tno.getText();

    Java ReferencePoint Suite 29

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    32/34

    if (no1.length()==0){getAppletContext().showStatus("Order No not

    to keep blank");}

    }}

    }

    You use the keyword implements to implement the ActionListener interface. When you click theAccept button, an ActionEvent object is generated. In the actionPerformed() method, the referenceto the event source is retrieved using the getSource() method. Use the showStatus() method todisplay the message on the status bar.

    The output of the code is shown in Figure 2530:

    Figure 2530: Applet Showing a Data Entry Validation Form

    Java ReferencePoint Suite 30

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    33/34

    Using Threads in a Swing ApplicationA thread is the smallest unit of an application that is executed by a microprocessor. For example,when you play a computer game, the graphics are displayed and the sound is played,simultaneously. You can use threads in areas, such as graphics or text animation.

    Listing 2520 contains the code to use threads in an application:

    Listing 2520: Using Thread in a Swing Application

    import javax.swing.*;import java.applet.*;import java.util.Date;import java.util.Calendar;import java.util.GregorianCalendar;public class Thread_example extends JApplet implements Runnable{JLabel name;JLabel add;Thread datetime;Date date;GregorianCalendar calendar;String strdate,strtime,strstatus;

    public void init(){name=new JLabel("name");add=new JLabel("address");JPanel p=new JPanel();getContentPane().add(p);p.add(name);p.add(add);datetime=new Thread(this);datetime.start();}public void run(){while (datetime!=null)

    {display();try{datetime.sleep(1000);}

    catch(InterruptedException e){ showStatus("thread interrupted");}

    }}

    public void display(){try{

    date=new Date();calendar=new GregorianCalendar();calendar.setTime(date);strtime=calendar.get(Calendar.HOUR)+":" +calendar.get(Calendar.MINUTE)+":"+calendar.get(Calstrdate=calendar.get(Calendar.MONTH)+"/" +calendar.get(Calendar.DATE)+"/" +calendar.get(Calstrstatus=strtime+" "+strdate;showStatus(strstatus);

    }catch(Exception e)

    {}}

    }

    The program imports the utility package that contains three classes: Date, Calendar, andGregorianCalendar. The Date class encapsulates the system date and time. GregorianCalendarextends from the Calendar class and displays dates according to the Gregorian calendar. TheRunnable interface contains the run()method that is executed when the thread is activated. The thiskeyword signifies that the run() method should be invoked. Use the start() method to start the

    Reprinted for v697039, Verizon SkillSoft, SkillSoft Corporation (c) 2002, Copying Prohibited

  • 7/29/2019 Creating GUI with Swing.pdf

    34/34

    thread. The setTime() method takes the Date object as an argument. Use the showStatus() methodto display the date and time on the status bar of the browser.

    The output of the code is shown in Figure 2531:

    Figure 2531: Applet Showing a Thread Example

    Java ReferencePoint Suite 32