java GUI programming


                            Applets , Awt And Event Handling
Till now we are printing the output in CUI(character user interface) without  graphics.
   So by using Applets and Awt java is providing GUI(graphical user interface ).
1. Applet is a  tiny code execute in Browser.
2.Browser and AppletViewer use to run Applets.
3.Doesnt have main method .
4.Residing at Serverside.
5.Asks a prompt to download.
6. java.awt package will provides the components to get  Textbox,Button etc.
7. to create an applet Class , so we need to extend our class from java.applet.Applet class.
8.Applet consists of lifecycle methods as follows
1.init():--
 This method gets called as soon as the applet is started.Initialisation of all
Variables,creation of objects,setting of parameters etc, can be done in this method.
2.start():--
 This method is executed after the init().The excution begins from start() method.
3.stop():--
 The moment Web page is exiting it will be called.
4.destroy():--
Is used to free the memory allocated by the variables and objects initialized by the applet.
5.paint():--
 Helps in drawing,writing, and creating a colored background to the applet.
9. it uses paint(Graphis g)—to do graphics we use this method.
10. to perform events we have java.awt.event package which provides classes and interfaces to perform event handling in applets programming.
/*<applet CODE="MyFirstApplet.class" width=400 height=400></applet>*/
import java.awt.*;
public class MyFirstApplet extends java.applet.Applet {
      public void paint(Graphics g) {
                              g.drawString("My first java Applet",78,30);
                  }
}
Compile the above code and Create a html page with bellow code
<applet CODE="MyFirstApplet.class" width=400 height=400></applet>
Save as  first.html .
Go to start-run-cmd—cd give folder path—
D:\core\>appletviewer first.html         //It runs the applet
Or  double click on first.html –it executes the applet application.
Ex.2.
//passing parameters to Applet
import java.awt.*;
public class ParamtestApplet extends java.applet.Applet  {
      Font f = new Font("TimesRoman",Font.BOLD,40);
      String name;
      public  void init() {
                   name=getParameter("name");
                  if(name==null)
                              name="friend";
                  name="have a nice day " +name;                                           
      }
      public void Paint(Graphics g) {
                  g.setFont(f);
                  g.setColor(Color.darkGray);
                  g.drawString(name,50,50);
} }
<applet CODE="ParamtestApplet.class" width=400 height=400>
<align=top>
<param name=name value="admin">
</applet>
Event Handling In Java
In any Interactive Environment, the program should be able to respond to respond performed by the user.The actions can be, mouse click,key press, selection of menu item.
  Java’s Abstract windowing toolkit (AWT) communicates these actions to the program using events. If Events are there we need to implement its related Listener’s, these listens and  performs some action.
The event listeners---
1.Mouselistener
2.MouseMotionListener.
3.Keylistener.
The awt  is a package of classes that help in creating full-fledged windowing Applications and Applets.. The COMPONENT class, which is the base class of all user interface Containers, provides the basic functionality needed for display and Event Handling. The Containers are Generic AWT Components that can contain other  Components including other Containers.
LayOut Managers
The Layout Manager is a set of classes that help in arranging the user interface components in a container.It determines how the components are sized and positioned inside the window.
These layouts are situated in java.awt package.
Types of layouts are:
1.Flowlayout(default for applets )
2.BorderLayout
3.GridLayout…etc.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class ActionExample extends Applet implements ActionListener{
      Button okButton;
      Button wrongButton;
      TextField nameField;
      CheckboxGroup radioGroup;
      Checkbox radio1;
      Checkbox radio2;
      Checkbox radio3;
      public void init() {
                  // Now we will use the Flow Layout
                  setLayout(new FlowLayout());
                  okButton = new Button("Action!");
                  wrongButton = new Button("Don't click!");
                  nameField = new TextField("Type here Something",35);
                  radioGroup = new CheckboxGroup();
                  radio1 = new Checkbox("Red", radioGroup,false);
                  radio2 = new Checkbox("Blue", radioGroup,true);
                  radio3 = new Checkbox("Green", radioGroup,false);
                  add(okButton);
                  add(wrongButton);
                  add(nameField);
                  add(radio1);
                  add(radio2);
                  add(radio3);
                  // Attach actions to the components
                  okButton.addActionListener(this);
                  wrongButton.addActionListener(this);
      }
      // Here we will show the results of our actions
      public void paint(Graphics g){
                  // If the radio1 box is selected then radio1.getState() will
                  // return true and this will execute
                  if (radio1.getState()) g.setColor(Color.red);
                  // If it was not red we'll try if it is blue
                  else if (radio2.getState()) g.setColor(Color.blue);
                  // Since always one radiobutton must be selected it must be green
                  else g.setColor(Color.green);
                  // Now that the color is set you can get the text out the TextField
                  // like this
                  g.drawString(nameField.getText(),20,100);
      }
      // When the button is clicked this method will get automatically called
      // This is where you specify all actions.
      public void actionPerformed(ActionEvent evt) {
                  // Here we will ask what component called this method
                  if (evt.getSource() == okButton) {    
                              // So it was the okButton, then let's perform his actions
                              // Let the applet perform Paint again.
                              // That will cause the aplet to get the text out of the textField
                              // again and show it.
                              repaint();
                  }
                  // Actions of the wrongButton
                  else if (evt.getSource() == wrongButton) {
                              // Change the text on the button for fun
                              wrongButton.setLabel("Not here!");
                              // Changes the text in the TextField
                              nameField.setText("That was the wrong button!");
                              // Lets the applet show that message.
                              repaint();
                  }
      }         
      }
Compile the above code and Create a html page with bellow code
<applet code="ActionExample.class" width=400 height=400></applet>
Save as  DrawEx.html .
Go to start-run-cmd—cd give folder path—
D:\core\>appletviewer DrawEx.html         //It runs the applet
Or  double click on DrawEx.html –it executes the applet application.
//mouse events example
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseTest extends Applet implements MouseListener,MouseMotionListener{
      public void init(){
                  addMouseListener(this);
                  addMouseMotionListener(this);
      }
      public void  mouseClicked(MouseEvent e) {
     showStatus("mouse clicked at " +e.getX()+","+e.getY());
      }
      public void  mouseEntered(MouseEvent e) {
     showStatus("mouse entered at " +e.getX()+","+e.getY());
      }
      public void  mouseExited(MouseEvent e) {
     showStatus("mouse exited at " +e.getX()+","+e.getY());
      }
      public void  mousePressed(MouseEvent e){
     showStatus("mouse Pressed at " +e.getX()+","+e.getY());
      }
      public void  mouseReleased(MouseEvent e) {
     showStatus("mouse released at " +e.getX()+","+e.getY());
      }
      public void  mouseDragged(MouseEvent e) {
     showStatus("mouse dragged at " +e.getX()+","+e.getY());
      }
      public void  mouseMoved(MouseEvent e) {
     showStatus("mouse Moved at " +e.getX()+","+e.getY());
      }
}
<applet code="MouseTest.class" width=200 height=200></applet>


Java Swings
Swings are used to provide GUI for a java application.these are  Pluggable Look & Feel Lightweight components. Swing, which is an extension library to the AWT, includes new and improved components that enhance the look and functionality of GUIs.  Swing can be used to build Standalone swing gui Apps as well as Servlets and Applets.  It employs a model/view design architecture. Swing is more portable and more flexible than AWT. Components from AWT and Swing can be mixed, allowing you to add Swing support to existing AWT-based programs. Swings classes and interfaces are available in “ javax.swing “ package .
Differences between Applets & Swings
1.Swing is light weght Component. Applet is heavy weight Components
2. Swing Using UIManager. Swing have look and feel according to user view u can change look and feel. Applet Does not provide this facility 
3.Swing uses for stand lone Applications ,Swing have main method to execute the program. Applet need HTML code for Run the Applet 
4. Swing have its own Layout ..like most popular Box Layout(card layout) Applet uses Awt Layouts..like flowlayout
5. Swing have some Thread rules. Applet doent have any rule.
Ex1 :-

import javax.swing.*;
import java.awt.*;
class MySwing extends JFrame{
            MySwing(){
                        JButton b1=new JButton("add");
                        Container c=getContentPane();
                        c.setLayout(new FlowLayout());
                        c.add(b1);
            }
            public static void main(String[] args) {
                        MySwing m=new MySwing();
                        m.setSize(300,300);
                        m.setVisible(true);
            }  
  }


Ex2 :-

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Check extends JFrame implements ItemListener, ActionListener{
            Container c=this.getContentPane();  
            JCheckBox r=new JCheckBox("RED");
            JCheckBox g=new JCheckBox("GREEN");
            JCheckBox b=new JCheckBox("BLUE");
            JButton jb=new JButton("Cancel");
            String l="";
            String msg="";
            public Check() {                     
                        c.setLayout(new FlowLayout());
                        JPanel jp1=new JPanel();
                        jp1.setLayout(new GridLayout(5,2));                       
                        jp1.add(r);
                        jp1 .add(g);
                        jp1.add(b);                 
                        c.add(jp1);
                        c.add(jb);                    
                        r.addItemListener(this); 
                        g.addItemListener(this);
                        b.addItemListener(this);
                        jb.addActionListener(this);                
                        setVisible(true);
                        setSize(200,200);       
            }         
            public void actionPerformed(ActionEvent e){
                        System.exit(0);
            }         
            public void itemStateChanged(ItemEvent ee){
                        if (r.isSelected()==true)
                                    c.setBackground(Color.red);
                        if (g.isSelected()==true)
                            c.setBackground(Color.green);
                        if (b.isSelected()==true)
                          c.setBackground(Color.blue);                                  
            }
            public static void main(String args[]) throws Exception{
                        Check c1=new Check();
            }
}



No comments:

Post a Comment