☰ Topics

GUI

Generally, we use Netbeans for designing GUI but Eclipse is for professional use, for designing web applications. We are familiar with HTML, HTML is also used for form designing but it designs only dead forms. Extra coding is needed for the functioning of HTML forms, which can be done in .Net, Java, PHP etc. GUI includes window applications, web applications and web services.

  1. Window Application: It can run only on window. It has several classes which contains several controls used for designing GUI's. For windows based applications, java.awt (Abstract Window Toolkit) package is used. This package contains all the classes for creating user interfaces and for painting graphics & image. It has 2D style, look & feel.

  2. Web Application: It includes Applet, JSP, Servlet. Some advanced web applications include MUC, Spring, Strats, Hibernet, JSF (Java Server Faces). Applet can run on both desktop and web browsers. Its security and functionality are more enhanced while working on browsers. Servlets run on web browsers. MUC, Spring, Strats, Hibernet and JSP provides advanced GUI with business logic.

  3. Mobile Application: The most common mobile application developed in JAVA is Android which is OS. It also provides environment, tools and API (Application Programming Interface).

  4. Web Services: Web Services has no user interface. It only provides services to many applications. For example, Cricket is handled by ICC, ICC has its own website and mobile application which provides cricket scores and other informations but there are many other website and applications which provides scores. All these websites uses the same database which ICC uses means ICC is providing services to all the websites. All booking engines like railway reservation, hotel booking etc belong to this category.

Classes of awt package:

Classes Controls
Label label
TextField textbox
Checkbox checkbox, radiobutton
Button button
Choice combobox (single selection)
Select Multiple Selection combobox
List listbox

Frame class is also the member of awt package. It is used to make blank form. There is a Component class which is an abstract class that encapsulates all of the attributes of a visual component. All user interface elements that are displayed on the screen and that interacts with the user are subclasses of Component. Container class is a subclass of Component. It contains all the control. There is a Panel class and DesktopPane class, which are similar to the Container class. Panel is used to separate the controls on the Frame for designing purpose to make it interactive. DesktopPane class is used for MDI applications.

Note: In MDI applications, child frame is inserted inside parent frame and one parent frame can contain multiple child frames. There is add() method with each control to add the control to the main container.

Program to create a frame

import java.awt.*;
public class exSwin extends Frame{
    public exswin(){
        super("First Frame");
        setSize(400,400);
        setVisible(true);
    }
    public static void main(String args[]){
        new exSwin();
    }
 }
  

Using Layout Managers: A layout manager automatically arranges your controls within a window. Each Container object has a layout manager associated with it. A layout manager is an instance of any class that implements LayoutManager interface. Different types of layouts are as follows:

  1. Flow Layout: It is the default layout. Components are laid out line by line (i.e. left to right).

  2. Grid Layout: It lays out components in a two-dimensional grid. Here we define the number of rows & columns. In the constructor of GridLayout we pass number of rows & number of columns as arguments. The substitue of GridLayout is GridBagLayout , here we can specify the relative placements of components by specifying their position within cells inside a grid.

  3. Border Layout: It has four sides (North, South, East, West) and one large area in center.

  4. Card Layout: This layout can be thought of as being on a separate index card in a desk that can be shuffled so that any card is on top at a given time. It is hidden one before the another. Example: Tab based system.

  5. Custom / User-defined Layout: We can set the pixel of the screen according to our requirement then we pass null for LayoutObject. Then to determine the shape and position of each component manually setBounds() method is used, inherited from Component. It has 4 arguments, i.e. starting value of x-coordinate, starting value of y-coordinate, length of control and width of control. The standard size of control is 20.

Important Terms:

An event is an object that describes a state change in a source. A source is an object that generates an event. Listener listens that which type of event occured, on which control it occured & passes it to Master Handler. The interface of a listener is ActionListener and it comes under java.awt.event package. The event for buttons is ActionEvent.

Program to enter name in textfield and print it in message dialog box:
import java.awt.*;        //For GUI
import java.awt.event.*;    //For event handling
import javax.swing.*;      //For advanced GUI
public class exwin extends Frame implements ActionListener       //Implementation of listener
{
  Label lb;         //Initialization of controls
  TextField tx;
  Button b;
  public exwin()
  {
    super("Window Example");
    setSize(400,400);
    setVisible(true);
    setLayout(null);      //For user-defined layout
    lb=new Label("Your name:");
    tx=new TextField(15);
    b=new Button("OK");
    lb.setBounds(50,50,100,20);     //For positioning the controls on the frame
    tx.setBounds(150,50,200,20);
    b.setBounds(90,100,50,20);
    add(lb);
    add(tx);
    add(b);
    b.addActionListener(this);      //Event source of button
  }
  public static void main(String[] arg)
  {
    new exwin();
  }
  public void actionPerformed(ActionEvent e)
  {
    if(e.getSource()==b)      //For comparison of event source
    {
      String s=tx.getText();
      JOptionPane.showMessageDialog(null,"Welcome "+s);     //Belongs to javax.swing Package
    }
  }
}                                                                  

                            

OUTPUT:

Controls

  1. Check Box: Checkbox and radio buttons belongs to Checkbox class but for using radio buttons we have to use one more class called CheckboxGroup class, it groups all check boxes into one group and allows one selection at a time. getState() is used to retrieve the current state of a check box. Return type is boolean. setState() is used to see the state of the checkbox. getLabel() is used to obtain the current level associated with a check box. setLabel() is used to set that level. Each time a checkbox is selected or deselected, an item event is generated. This is sent to ItemListener interface. And its handler is itemStateChanged() method defined in ItemListener interface. An ItemEvent object is supplied as the arguments to this method.

    Program to illustrate checkbox:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class excheck extends Frame implements ActionListener,ItemListener
    {
      Label lb;
      Button b1,b2;
      Checkbox c1,c2,c3;
      public excheck()
      {
        super("CheckBox Example");
        setSize(400,400);
        setVisible(true);
        setLayout(null);
        lb=new Label("Education Qualification");
        b1=new Button("SUBMIT");
        b2=new Button("EXIT");
        c1=new Checkbox("10");
        c2=new Checkbox("10+2");
        c3=new Checkbox("BCA");
        lb.setBounds(50,50,110,20);
        c1.setBounds(50,80,110,20);
        c2.setBounds(50,110,110,20);
        c3.setBounds(50,140,110,20);
        b1.setBounds(50,170,110,20);
        b2.setBounds(170,170,110,20);
        add(lb);
        add(b1);
        add(b2);
        add(c1);
        add(c2);
        add(c3);
        c1.addItemListener(this);
        c2.addItemListener(this);
        c3.addItemListener(this);
        b1.addActionListener(this);
        b2.addActionListener(this);
      }
      public static void main(String[] arg)
      {
        new excheck();
      }
      public void actionPerformed(ActionEvent e)
      {
         if(e.getSource()==b1)
         {
           String s="";
           if(c1.getState())
    	 s=s+c1.getLabel();
           if(c2.getState())
    	 s=s+" "+c2.getLabel();
           if(c3.getState())
    	 s=s+" "+c3.getLabel();
           JOptionPane.showMessageDialog(null,"You have selected "+s+" ");
         }
         if(e.getSource()==b2)
           System.exit(0);
      }
      public void itemStateChanged(ItemEvent e)
      {
         String s="";
         if(e.getItemSelectable()==c1)
    	s=c1.getLabel();
         if(e.getItemSelectable()==c2)
    	s=c2.getLabel();
         if(e.getItemSelectable()==c3)
    	s=c3.getLabel();
         JOptionPane.showMessageDialog(null,"You have selected "+s); 
      }
    }                                                                  
    
                                    

    OUTPUT:
    
    
  2. Radiobutton: 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 selected at a time. These check boxes are often called radiobutton and CheckboxGroup class is used for it. getSelectedCheckbox() is used to determine which check box in a group is currently selelcted. setSelectedCheckbox() is used to set a checkbox selected.

    Program to illustrate radiobutton
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class exradio extends Frame implements ActionListener,ItemListener
    {
      Label lb;
      Button b1,b2;
      Checkbox r1,r2;
      CheckboxGroup grp;
      public exradio()
      {
        super("Radio Button Example");
        setSize(400,400);
        setVisible(true);
        setLayout(null);
        lb=new Label("Select gender");
        b1=new Button("SUBMIT");
        b2=new Button("EXIT");
        grp=new CheckboxGroup();
        r1=new Checkbox("Male",grp,false);
        r2=new Checkbox("Female",grp,false);
        lb.setBounds(50,50,110,20);
        r1.setBounds(50,80,110,20);
        r2.setBounds(50,110,110,20);
        b1.setBounds(50,170,110,20);
        b2.setBounds(170,170,110,20);
        add(lb);
        add(b1);
        add(b2);
        add(r1);
        add(r2);
        r1.addItemListener(this);
        r2.addItemListener(this);
        b1.addActionListener(this);
        b2.addActionListener(this);
      }
      public static void main(String[] arg)
      {
        new exradio();
      }
      public void actionPerformed(ActionEvent e)
      {
         if(e.getSource()==b1)
         {
           String s="";
           if(r1.getState())
    	 s=r1.getLabel();
           if(r2.getState())
    	 s=r2.getLabel();
           JOptionPane.showMessageDialog(null,"You have selected "+s);
         }
         if(e.getSource()==b2)
           System.exit(0);
      }
      public void itemStateChanged(ItemEvent e)
      {
         String s="";
         if(e.getItemSelectable()==r1)
    	s=r1.getLabel();
         if(e.getItemSelectable()==r2)
    	s=r2.getLabel();
         JOptionPane.showMessageDialog(null,"You have selected "+s); 
      }
    }                                                                  
    
                                        

    OUTPUT:
    
    
  3. Dropdown (ComboBox): Radiobutton's substitute control is dropdown list. It belongs to Choice class. The Choice class is used to create a pop-up list of items from which the user may choose choice only defines the default constructor, which creates an empty list. add() is used to add the selection in the list. getSelectedIndex() determine which item is currently selected i.e. it returns the index number of the selected item (starting with 0). getSelectedItem() returns a string containing the name of the item. By default, the first item added to the list is selected. getItemCount() is used to obtain the no. of items in the list. select() is used to set the currently selected item. Its parameter can be either a zero-based integer index or a string that will match a name in the list. getItem() is used to obtain the name associated with the item at given index. It also works on ItemListener.

    Program to illustrate Combobox:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class exchoice extends Frame implements ActionListener,ItemListener
    {
      Label lb;
      Choice ch;
      Button b;
      public exchoice()
      {
        super("Choice Example");
        setSize(400,400);
        setVisible(true);
        setLayout(null);
        lb=new Label("Select city:");
        b=new Button("OK");
        ch=new Choice();
        ch.add("Patna");
        ch.add("Gaya");
        ch.add("Ranchi");
        ch.add("Delhi");
        ch.add("Kolkata");
        lb.setBounds(50,50,100,20);
        ch.setBounds(150,50,200,20);
        b.setBounds(90,100,50,20);
        add(lb);
        add(ch);
        add(b);
        b.addActionListener(this);
        ch.addItemListener(this);
      }
      public static void main(String[] arg)
      {
        new exchoice();
      }
      public void itemStateChanged(ItemEvent e)
      {
        String s=ch.getSelectedItem().toString();
        JOptionPane.showMessageDialog(null,"You have selected "+s);
      }
      public void actionPerformed(ActionEvent e)
      {
        if(e.getSource()==b)
        {
           String s=ch.getSelectedItem().toString();
           JOptionPane.showMessageDialog(null,"You have selected "+s);
        }
      }
    }                                                                  
    
                                        

    OUTPUT:
    
    

KeyEvent Class: A KeyEvent is generated when keyboard input occurs. It is handled by KeyListener. There are three types of key events which are identified by these integer constants: Key_Pressed, Key_Realeased & Key_Typed. It is must to override all these events, if not then they must be empty overridden. It can be captured on form and within control. The KeyPressed() and KeyReleased() methods are invoked when a key is pressed and released respectively. The keyTyped() method is invoked when a character has been entered. The object of KeyEvent class is defined as the parameters of these methods. getKeyChar() returns the character that was entered and getKeyCode() returns the key code i.e. its ascii equivalent. getKeyChar() do not return any character for some keys like Esc, Ctrl etc and it is difficult to remember to key codes of all the keys. For the solution of this, there is a concept of virtual keys which are static constants of KeyEvent class and it is binded with every keys. For eg: VK_0 through VK_9 and VK_A through VK_I defines the ASCII equivalents of the numbers and letters. There are some others like VK_ENTER, VK_ESCAPE, VK_CANCEL, VK_CONTROL etc.

Program to illustrate key events:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class exkey extends Frame implements KeyListener
{
  public exkey()
  {
    super("Key Example");
    setSize(400,400);
    setVisible(true);
    setLayout(null);
    addKeyListener(this);
  }
  public static void main(String[] arg)
  {
    new exkey();
  }
  public void keyTyped(KeyEvent e)
  {
  }
  public void keyPressed(KeyEvent e)
  {
    if(e.getKeyCode()==e.VK_ENTER)
	JOptionPane.showMessageDialog(null,"You have pressed Enter");
    if(e.isControlDown() && e.getKeyCode()==e.VK_S)
	JOptionPane.showMessageDialog(null,"You have pressed shortcut key for save");
  }
  public void keyReleased(KeyEvent e)
  {
  }
}                                                                  

                            

OUTPUT:
When we press Enter key

MouseEvent Class: A MouseEvent is handled by MouseListener. There are 5 types of mouse events. Here, also it is must to override all these events.

  1. mouseClicked (MouseEvent e)
  2. mouseEntered (MouseEvent e)
  3. mouseExited (MouseEvent e)
  4. mousePressed (MouseEvent e)
  5. mouseReleased (MouseEvent e)

If the mouse is pressed and released at the same point, moseClicked() is invoked. When the mouse enters a component, mouseEntered() method is called. When it leaves, mouseExited() is called. The mousePressed() and mouseReleased() methods are invoked when the mouse is pressed and released respectively. The object of MouseEvent class is defined as the parameter of these methods. getX() return the value of x-coordinate of component where the mouse event the mouse event has occured and getY() returns the value of y-coordinate.

Program to illustrate mouse events:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class exmouse extends Frame implements MouseListener
{
  int x1,x2,y1,y2;
  public exmouse()
  {
    super("Mouse Example");
    setSize(400,400);
    setVisible(true);
    setLayout(null);
    addMouseListener(this);
  }
  public static void main(String[] arg)
  {
    new exmouse();
  }
  public void mouseClicked(MouseEvent e)
  {
    //JOptionPane.showMessageDialog(null,"Mouse CLicked");
  }
  public void mouseEntered(MouseEvent e)
  {
    //JOptionPane.showMessageDialog(null,"Mouse Entered");
  }
  public void mouseExited(MouseEvent e)
  {
    //JOptionPane.showMessageDialog(null,"Mouse Exited");
  }
  public void mousePressed(MouseEvent e)
  {
    x1=e.getX();
    y1=e.getY();
    //JOptionPane.showMessageDialog(null,"Mouse Pressed at"+x1+":"+y1);
  }
  public void mouseReleased(MouseEvent e)
  {
    x2=e.getX();
    y2=e.getY();
    repaint();
    JOptionPane.showMessageDialog(null,"Mouse Released");
  }
  public void paint(Graphics g)
  {
    g.setColor(new Color(255,100,100));
   // g.drawRect(x1,y1,x2,y2);
    g.fillRect(x1,y1,x2,y2);
  }
}                                                                  

                            

OUTPUT:
Draw the rectangle with mouse and then release the mouse

Menu Bars and Menus: A menubar contains one or more Menu objects. Each Menu object contains a list of MenuItem objects. Each MenuItem is something which is selected by the user. To create a menubar, first create an instance of MenuBar. A menubar contains one or more Menu objects. Each MenuItem object represents something that can be selected by the user. Since, Menu ia a subclass of MenuItem, a hierarchy of nested submenus can be created. It is also possible to include checkable menuitems. These are menu options of type CheckboxMenuItem and will have a check mark next to them when they are selected. There is no event of MenuBar and Menu, event is generated only when MenuItem is selected. ActionListener and Listener interfaces must be implemented in order to handle these menu events. Icons with menu can be implemented using Swing package.

Program to illustrate Menus:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class exmenu extends Frame implements ActionListener
{
  MenuBar mb;
  Menu m1,m2;
  MenuItem mi1,mi2,mi3,mi4;
  public exmenu()
  {
    super("Menu Example");
    setSize(400,400);
    setVisible(true);
    setLayout(null);
    mb=new MenuBar();
    setMenuBar(mb);
    m1=new Menu("File");
    m2=new Menu("Edit");
    mb.add(m1);
    mb.add(m2);
    mi1=new MenuItem("Calculator");
    mi2=new MenuItem("Choice Example");
    mi3=new MenuItem("Mouse Example");
    mi4=new MenuItem("Key Example");
    m1.add(mi1);
    m1.add(mi2);
    m1.add(mi3);
    m1.add(mi4);
    mi1.addActionListener(this);
    mi2.addActionListener(this);
    mi3.addActionListener(this);
    mi4.addActionListener(this);
  }
  public static void main(String[] arg)
  {
    new exmenu();
  }
  public void actionPerformed(ActionEvent e)
  {
    if(e.getSource()==mi1)
	new exwin1();
    if(e.getSource()==mi2)
	new exchoice();
    if(e.getSource()==mi3)
	new exmouse();
    if(e.getSource()==mi4)
	new exkey();
  }
}                                                                  

                            

OUTPUT: