UNIT 5 GUI Programming with java The AWT Class hierarchy Java AWT ( A b s t r ac t W i nd o w T o o l k i t ) i s an A P I (Application Programming Interface) to d eve lop GU I or w ind o w - b a s e d applications in java. Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavyweight i.e. its components are using the resources of OS. The java.awt package provides classes for AWT api such as TextField , Label, TextArea , RadioButton , CheckBox , Choice, List etc.
Java AWT Hierarchy The hierarchy of Java AWT classes are given below.
Container The Container is a component in AWT that can contain another components like buttons, textfields , labels etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel. Window The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating a window. Panel The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield etc. Frame The Frame is the container that contain title bar and can have menu bars. It can have other components like button, textfield etc.
Useful Methods of Component class Method Description public void add(Component c) inserts a component in container public void setSize(int width,int height) sets the size (width and height) of the component. public void setLayout(LayoutManager m) defines the layout manager for the component. public void setVisible(boolean status) changes the visibility of the component, by default false.
Java AWT Example To create simple awt example, you need a frame. There are two ways to create a frame in AWT. By extending Frame class (inheritance) By creating the object of Frame class (association) AWT Example by Inheritance Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button component on the Frame. import java.awt.*; class First extends Frame{ First(){ Button b= new Button( "click me" ); b.setBounds ( 30 , 100 , 80 , 30 ); // setting button position add(b); //adding button into frame setSize ( 300 , 300 ); //frame size 300 width and 300 height setLayout ( null ); //no layout manager setVisible ( true ); //now frame will be visible, by default not visible } public static void main(String args []){ First f= new First(); }}
The setBounds ( int xaxis , int yaxis , int width, int height) method is used in the above example that sets the position of the awt button.
By creating the object of Frame class (association) import java.awt.*; class First { First() { Frame f=new Frame(); Button b= new Button( "click me" ); b.setBounds ( 30 , 100 , 80 , 30 ); // setting button position f. add (b); //adding button into frame f. setSize ( 300 , 300 ); //frame size 300 width and 300 height f. setLayout ( null ); //no layout manager f.setVisible ( true ); //now frame will be visible, by default not visible } public static void main(String args []){ First f= new First(); }}
Difference between AWT and Swing No. Java AWT Java Swing 1) AWT components dependent . are platform- Java swing components are platform- independent . 2) AWT components are heavyweight . Swing components are lightweight . 3) AWT doesn't support pluggable look and feel . Swing supports pluggable look and feel . 4) AWT provides less Swing. components than Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser, tabbedpane etc. 5) AWT doesn't follows MVC (Model View Controller) where model represents data, view represents presentation and controller acts as an interface between model and view. Swing follows MVC .
L 5.1
L 5.2 Model Model consists of data and the functions that operate on data Java bean that we use to store data is a model component EJB can also be used as a model component
L 5.3 view View is the front end that user interact. View can be a HTML JSP Struts ActionForm
L 5.4 Controller Controller component responsibilities Receive request from client Map request to specific business operation Determine the view to display based on the result of the business operation
Java Swing Java Swing is a part of Java Foundation Classes (JFC) that is used to create window- based applications . It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java. Unlike AWT, Java Swing provides platform-independent and lightweight components. The javax.swing package provides classes for java swing API such as JButton , JTextField , JTextArea , JRadioButton , JCheckbox , JMenu , JColorChooser etc.
Hierarchy of Java Swing classes
Commonly used Methods of Component class Method Description public void add(Component c) add a component on another component. public void setSize(int width,int height) sets size of the component. public void setLayout(LayoutManager m) sets the layout manager for the component. public void setVisible(boolean b) sets the visibility of the component. It is by default false.
Java Swing Examples There are two ways to create a frame: By extending Frame class (inheritance) By creating the object of Frame class (association) We can write the code of swing inside the main(), constructor or any other method. Simple Java Swing Example Let's see a simple swing example where we are creating one button and adding it on the JFrame object inside the main() method.
FirstSwingExample.java import javax.swing .*; public class FirstSwingExample { public static void main(String[] args ) { JFrame f= new JFrame (); //creating instance of JFrame JButton b= new JButton ( " clickme " ); //creating instance of JButton b.setBounds ( 130 , 100 , 100 , 40 ); //x axis, y axis, width, height f.add (b); //adding button in JFrame f.setSize ( 400 , 500 ); //400 width and 500 height f.setLayout ( null ); //using no layout managers f.setVisible ( true ); //making the frame visible } }
Simple example of Swing by inheritance import  javax.swing .*;  public  class  Simple2 extends  JFrame {//inheriting JFrame   JFrame  f;  Simple2(){  JButton  b= new  JButton ("click");//create button  b.setBounds (130,100,100, 40);            add(b);//adding button on frame  setSize (400,500);  setLayout ( null );  setVisible ( true );  }  public  static  void  main(String[] args ) {  new  Simple2();  }} Â
Overview of Swing Components Java JButton The JButton class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed. It inherits AbstractButton class. JButton class declaration Let's see the declaration for javax.swing.JButton class. public  class  JButton  extends  AbstractButton  implements  Accessible  Commonly used Constructors: Constructor Description JButton() It creates a button with no text and icon. JButton(String s) It creates a button with the specified text. JButton(Icon i) It creates a button with the specified icon object.
Methods Description void setText(String s) It is used to set specified text on button String getText() It is used to return the text of the button. void setEnabled(boolean b) It is used to enable or disable the button. void setIcon (Icon b) It is used to set the specified Icon on the button. Icon getIcon() It is used to get the Icon of the button. void setMnemonic(int a) It is used to set the mnemonic on the button. void addActionListener(ActionListener a) It is used to add the action listener  to this object. Commonly used Methods of AbstractButton class:
Java JButton Example import  javax.swing .*;    public  class  ButtonExample  {  public  static  void  main(String[] args ) {      JFrame  f= new  JFrame ("Button Example");      JButton  b= new  JButton ("Click Here");      b.setBounds (50,100,95,30);      f.add (b);      f.setSize (400,400);      f.setLayout ( null );      f.setVisible ( true );   }  } Â
Example of displaying image on the button : import  javax.swing .*;      public  class  ButtonExample {    ButtonExample (){    JFrame  f= new  JFrame ("Button Example");            JButton  b= new  JButton ( new  ImageIcon ("D:\\icon.png"));    b.setBounds (100,100,100, 40);    f.add (b);    f.setSize (300,400);    f.setLayout ( null );    f.setVisible ( true );    f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );        }         public  static  void  main(String[] args )  {        new  ButtonExample ();    }    }   Â
Java JLabel The object of JLabel class is a component for placing text in a container. It is used to display a single line of read only text. The text can be changed by an application but a user cannot edit it directly. It inherits JComponent class . JLabel class declaration Let's see the declaration for javax.swing.JLabel class. public  class  JLabel  extends  JComponent  implements  SwingConstants , Accessible  Constructor Description JLabel() Creates a JLabel instance with no image and with an empty string for the title. JLabel(String s) Creates a JLabel instance with the specified text. JLabel (Icon i) Creates a JLabel instance with the specified image. JLabel(String s, Icon i, int horizontalAlignment) Creates a JLabel instance with the specified text, image, and horizontal alignment. Commonly used Constructors:
Methods Description String getText() t returns the text string that a label displays. void setText (String text) It defines the single line of text this component will display. void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along the X axis. Icon getIcon() It returns the graphic image that the label displays. int getHorizontalAlignment() It returns the alignment of the label's contents along the X axis. Commonly used Methods:
Java JLabel Example import  javax.swing .*;  class  LabelExample   {  public  static  void  main(String args [])      {      JFrame  f= new  JFrame ("Label Example");      JLabel  l1,l2;      l1= new  JLabel ("First Label.");      l1.setBounds(50,50, 100,30);      l2= new  JLabel ("Second Label.");      l2.setBounds(50,100, 100,30);      f.add (l1); f.add (l2);      f.setSize (300,300);      f.setLayout ( null );      f.setVisible ( true );      }      } Â
Java JTextField The object of a JTextField class is a text component that allows the editing of a single line text. It inherits JTextComponent class . Constructor Description JTextField() Creates a new TextField JTextField (String text) Creates a new TextField initialized with the specified text. JTextField(String text, int columns) Creates a new TextField initialized with the specified text and columns. JTextField(int columns) Creates a new empty TextField with the specified number of columns. Commonly used Constructors:
Methods Description void addActionListener(ActionListener l) It is used to add the specified action listener to receive action events from this textfield. Action getAction () It returns the currently set Action for this ActionEvent source, or null if no Action is set. void setFont(Font f) It is used to set the current font. void removeActionListener(ActionListener l) It is used to remove the specified action listener so that it no longer receives action events from this textfield . Commonly used Methods:
Java JTextField Example import  javax.swing .*;  class  TextFieldExample   {  public  static  void  main(String args [])      {      JFrame  f= new  JFrame (" TextField  Example");      JTextField  t1,t2;      t1= new  JTextField ("Welcome to Java.");       t1.setBounds(50,100, 200,30);      t2= new  JTextField (“welcome");       t2.setBounds(50,150, 200,30);      f.add (t1); f.add (t2);      f.setSize (400,400);      f.setLayout ( null );      f.setVisible ( true );      }      } Â
Containers Java Jframe: The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class. JFrame works like the main window where components like labels, buttons, textfields are added to create a GUI. Unlike Frame, JFrame has the option to hide or close the window with the help of setDefaultCloseOperation ( int ) method. JFrame Example import java.awt.FlowLayout ; import javax.swing.JButton ; import javax.swing.JFrame ; import javax.swing.JLabel ; import javax.swing.Jpanel ; public class JFrameExample { public static void main(String s[]) { JFrame frame = new JFrame ( " JFrame Example" ); JPanel panel = new JPanel (); panel.setLayout ( new lowLayout ());
JApplet As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The JApplet class extends the Applet class. Example of EventHandling in JApplet : import java.applet .*; import javax.swing .*; import java.awt.event .*; public class EventJApplet extends JApplet implements ActionListener { JButton b; JTextField tf ; public void init () { tf = new JTextField (); tf.setBounds ( 30 , 40 , 150 , 20 ); b= new JButton ( "Click" ); b.setBounds ( 80 , 150 , 70 , 40 ); add(b); add( tf ); b.addActionListener ( this );
setLayout ( null ); } public void actionPerformed ( ActionEvent e) { tf.setText ( "Welcome" ); } } In the above example, we have created all the controls in init() method because it is invoked only once. myapplet.html <html> <body> <applet code= " EventJApplet.class " width= "300" height= "300" > </applet> </body> </html>
JDialog The JDialog control represents a top level window with a border and a title used to take some form of input from the user. It inherits the Dialog class. Unlike JFrame , it doesn't have maximize and minimize buttons. JDialog class declaration Let's see the declaration for javax.swing.JDialog class. public class JDialog extends Dialog implements WindowConstants , Accessible, RootPaneConta iner . Commonly used Constructors Constructor Description JDialog() It is used to create a modeless dialog without a title and without a specified Frame owner. JDialog(Frame owner) It is used to create a modeless dialog with specified Frame as its owner and an empty title. JDialog(Frame owner, String title, boolean modal) It is used to create a dialog with the specified title, owner Frame and modality.
Java JDialog Example import javax.swing .*; import java.awt.*; import java.awt.event .*; public class DialogExample { private static JDialog d; DialogExample () { JFrame f= new JFrame (); d = new JDialog (f , "Dialog Example" , true ); d.setLayout ( new FlowLayout () ); JButton b = new JButton ( "OK" ); b.addActionListener ( new ActionListener () { public void actionPerformed ( ActionEvent e ) { DialogExample.d.setVisible ( false ); } } )
d.add ( new JLabel ( "Click button to continue." )); d.add (b); d.setSize ( 300 , 300 ); d.setVisible ( true ); } public static void main(String args []) { new DialogExample (); } }
JPanel The JPanel is a simplest container class. It provides space in which an application can attach any other component. It inherits the JComponents class. It doesn't have title bar. JPanel class declaration public class JPanel extends JComponent implements Accessible Java JPanel Example import java.awt.*; import javax.swing .*; public class PanelExample { PanelExample () { JFrame f= new JFrame ( "Panel Example" ); JPanel panel= new JPanel (); panel.setBounds ( 40 , 80 , 200 , 200 ); panel.setBackground ( Color.gray ); JButton b1= new JButton ( "Button 1" ); b1.setBounds( 50 , 100 , 80 , 30 ); b1.setBackground( Color.yellow );
JButton b2= new JButton ( "Button 2" ); b2.setBounds( 100 , 100 , 80 , 30 ); b2.setBackground( Color.green ); panel.add (b1); panel.add (b2); f.add (panel); f.setSize ( 400 , 400 ); f.setLayout ( null ); f . s e t V i s i b l e ( t r ue ); } public static void main(String args []) { new PanelExample (); } }
Check boxes The JCheckBox class, which provides the functionality of a check box, is a concrete implementation of AbstractButton . Some of its constructors are shown here: JCheckBox(Icon i) JCheckBox(Icon i, boolean state) JCheckBox(String s) JCheckBox(String s, boolean state) JCheckBox(String s, Icon i) JCheckBox(String s, Icon i, boolean state) Here, i is the icon for the button. The text is specified by s . If state is true , the check box is initially selected. Otherwise, it is not. The state of the check box can be changed via the following method: void setSelected(boolean state) Here, state is true if the check box should be checked.
Scroll Panes Scrollbar generates adjustment events when the scroll bar is manipulated. Scrollbar creates a scroll bar control. Scroll bars are used to select continuous values between a specified minimum and maximum. Scroll bars may be oriented horizontally or vertically. A scroll bar is actually a composite of several individual parts. Each end has an arrow that you can click to move the current value of the scroll bar one unit in the direction of the arrow. The current value of the scroll bar relative to its minimum and maximum values is indicated by the slider box (or thumb ) for the scroll bar. The slider box can be dragged by the user to a new position. The scroll bar will then reflect this value.
Scrollbar defines the following constructors: Scrollbar( ) Scrollbar( int style) Scrollbar( int style, int initialValue , int thumbSize , int min, int max) The first form creates a vertical scroll bar. The second and third forms allow you to specify the orientation of the scroll bar. If style is Scrollbar.VERTICAL , a vertical scroll bar is created. If style is Scrollbar.HORIZONTAL , the scroll bar is horizontal. In the third form of the constructor, the initial value of the scroll bar is passed in initialValue . The number of units represented by the height of the thumb is passed in thumbSize . The minimum and maximum values for the scroll bar are specified by min and max. vertSB = new Scrollbar( Scrollbar.VERTICAL , 0, 1, 0, height); horzSB = new Scrollbar( Scrollbar.HORIZONTAL , 0, 1, 0, width);
Combo Box Swing provides a combo box (a combination of a text field and a drop-down list) through the JComboBox class, which extends JComponent . A combo box normally displays one entry. However, it can also display a drop-down list that allows a user to select a different entry. You can also type your selection into the text field. Two of JComboBox 's constructors are : JComboBox( ) JComboBox(Vector v) Here, v is a vector that initializes the combo box. Items are added to the list of choices via the addItem( ) method, whose signature is: void addItem(Object obj) Here, obj is the object to be added to the combo box.
Radio Button Radio buttons are supported by the JRadioButton class, which is a concrete implementation of AbstractButton . Some of its constructors are : JRadioButton(Icon i) JRadioButton(Icon i, boolean state) JRadioButton(String s) JRadioButton(String s, boolean state) JRadioButton(String s, Icon i) JRadioButton(String s, Icon i, boolean state) Here, i is the icon for the button. The text is specified by s . If state is true , the button is initially selected. Otherwise, it is not. Elements are then added to the button group via the following method: void add(AbstractButton ab) Here, ab is a reference to the button to be added to the group.
L 6.6 check box groups It is possible to create a set of mutually exclusive check boxes in which one and only one check box in the group can be checked at any one time. These check boxes are oftenccalled radio buttons. To create a set of mutually exclusive check boxes, you must first define the group to which they will belong and then specify that group when you construct the check boxes. Check box groups are objects of type CheckboxGroup . Only the default constructor is defined, which creates an empty group. To determine which check box in a group is currently selected by calling getSelectedCheckbox( ) . To set a check box by calling setSelectedCheckbox( ) . These methods are as follows: Checkbox getSelectedCheckbox( ) void setSelectedCheckbox(Checkbox which) Here, which is the check box that you want to be selected. The previously selected checkbox will be turned off. CheckboxGroup cbg = new CheckboxGroup(); Win98 = new Checkbox("Windows 98", cbg, true); winNT = new Checkbox("Windows NT", cbg, false);
L 6.7 choices The Choice class is used to create a pop-up list of items from which the user may choose. A Choice control is a form of menu. Choice only defines the default constructor, which creates an empty list. To add a selection to the list, call addItem( ) or add( ) . void addItem(String name) void add(String name) Here, name is the name of the item being added. Items are added to the list in the order to determine which item is currently selected, you may call either getSelectedItem( ) or getSelectedIndex( ) . String getSelectedItem( ) int getSelectedIndex( )
Tabbed Panes A tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder has a title. When a user selects a folder, its contents become visible. Only one of the folders may be selected at a time. Tabbed panes are commonly used for setting configuration options. Tabbed panes are encapsulated by the JTabbedPane class, which extends JComponent . We will use its default constructor. Tabs are defined via the following method: void addTab(String str, Component comp) Here, str is the title for the tab, and comp is the component that should be added to the tab. Typically, a JPanel or a subclass of it is added. The general procedure to use a tabbed pane in an applet is outlined here: 1. Create a JTabbedPane object. 2. Call addTab( ) to add a tab to the pane. (The arguments to this method define the title of the tab and the component it contains.) 3. Repeat step 2 for each tab. 4. Add the tabbed pane to the content pane of the applet.
Tabels A table is a component that displays rows and columns of data. You can drag the cursor on column boundaries to resize columns. You can also drag a column to a new position. Tables are implemented by the JTable class, which extends JComponent . One of its constructors is : JTable(Object data[ ][ ], Object colHeads[ ]) Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-dimensional array with the column headings. Here are the steps for using a table in an applet: 1. Create a JTable object. 2. Create a JScrollPane object. (The arguments to the constructor specify the table and the policies for vertical and horizontal scroll bars.) 3. Add the table to the scroll pane. 4. Add the scroll pane to the content pane of the applet.
Layout Manager types The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented by all the classes of layout managers. There are following classes that represents the layout managers: java.awt.BorderLayout java.awt.FlowLayout java.awt.GridLayout java.awt.CardLayout java.awt.GridBagLayout javax.swing.BoxLayout javax.swing.GroupLayout javax.swing.ScrollPaneLayout javax.swing.SpringLayout etc.
BorderLayout The BorderLayout provides five constants for each region: public static final int NORTH public static final int SOUTH public static final int EAST public static final int WEST public static final int CENTER Constructors of BorderLayout class: BorderLayout (): creates a border layout but with no gaps between the components. JBorderLayout ( int hgap , int vgap ): creates a border layout with the given horizontal and vertical gaps between the components.
Example of BorderLayout class: import java.awt.*; import javax.swing .*; public class Border { JFrame f; Border() { f= new JFrame (); JButton b1= new JButton ( "NORTH" ); JButton b2= new JButton ( "SOUTH" ); JButton b3= new JButton ( "EAST" ); JButton b4= new JButton ( "WEST" ); JButton b5= new JButton ( "CENTER" ); f.add (b1,BorderLayout.NORTH); f.add (b2,BorderLayout.SOUTH); f.add (b3,BorderLayout.EAST); f.add (b4,BorderLayout.WEST); f.add (b5,BorderLayout.CENTER); f.setSize ( 300 , 300 ); f.setVisible ( true ); } public static void main(String[] args ) { new Border(); } }
GridLayout The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle . Constructors of GridLayout class GridLayout (): creates a grid layout with one column per component in a row. GridLayout ( int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the components. GridLayout ( int rows, int columns, int hgap , int vgap ): creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps. Example of GridLayout class import java.awt .*; import javax.swing .*; public class MyGridLayout { JFrame f; MyGridLayout (){ f= new JFrame (); JButton b1= new JButton ( "1 " ); JButton b2= new JButton ( "2" ); JButton b3= new JButton ( "3" ); JButton b4= new JButton ( "4" ); JButton b5= new JButton ( "5" ); JButton b6= new JButton ( "6" ); JButton b7= new JButton ( "7" ); JButton b8= new JButton ( "8" ); JButton b9= new JButton ( "9" );
f.add (b1 ); f.add (b2); f.add (b3); f.add (b4); f.add (b5 ); f.add (b6 ); f.add (b7); f.add (b8); f.add (b9 ); f .setLayout ( new GridLayout ( 3 , 3 )); // setting grid layout of 3 rows and 3 columns f.setSize ( 300 , 300 ); etVisible ( true ); } public static void main(String[] args ) { new MyGridLayout (); }} Java FlowLayout The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel. Fields of FlowLayout class public static final int LEFT public static final int RIGHT public static final int CENTER
Constructors of FlowLayout class FlowLayout (): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap. FlowLayout ( int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical gap. FlowLayout ( int align, int hgap , int vgap ): creates a flow layout with the given alignment and the given horizontal and vertical gap. import java.awt .*; import javax.swing .*; public class MyFlowLayout { JFrame f; MyFlowLayout () { f= new JFrame (); JButton b1= new JButton ( "1" ); JButton b2= new JButton ( "2" ); JButton b3= new JButton ( "3" ); JButton b4= new JButton ( "4" ); JButton b5= new JButton ( "5" ); f.add (b1); f.add (b2); f.add (b3); f.add (b4); f.add (b5); f.setLayout ( new FlowLayout ( FlowLayout.RIGHT )); //setting flow layout of right alignment f.setSize ( 300 , 300 ); f.setVisible ( true ); } public static void main(String[] args ) { new MyFlowLayout (); } }
L 9.6 Card layout The CardLayout class is unique among the other layout managers in that it stores several different layouts. Each layout can be thought of as being on a separate index card in a deck that can be shuffled so that any card is on top at a given time. CardLayout provides these two constructors: CardLayout( ) CardLayout(int horz, int vert) The cards are held in an object of type Panel . This panel must have CardLayout selected as its layout manager. Cards are added to panel using void add(Component panelObj, Object name); methods defined by CardLayout : void first(Container deck) void last(Container deck) void next(Container deck) void previous(Container deck) void show(Container deck, String cardName)
L 9.7 GridBag Layout The Grid bag layout displays components subject to the constraints specified by GridBagConstraints. GridLayout lays out components in a two-dimensional grid. The constructors are GridLayout( ) GridLayout(int numRows, int numColumns ) GridLayout(int numRows, int numColumns, int horz, int vert)