google-site-verification: googled768248d3fb0e357.html Youth Stuff: A Demo on JAVA Package AWT (Abstract Window Toolkit)

Monday, 17 June 2013

A Demo on JAVA Package AWT (Abstract Window Toolkit)

Button Example.
import java.awt.*; 
import java.awt.event.*; 
 
public class ButtonPressDemo { 
  public static void main(String[] args){ 
  Button b; 
  ActionListener a = new MyActionListener(); 
  Frame f = new Frame("Java Applet"); 
  f.add(b = new Button("Bonjour"), BorderLayout.NORTH); 
  b.setActionCommand("Good Morning"); 
  b.addActionListener(a); 
  f.add(b = new Button("Good Day"), BorderLayout.CENTER); 
  b.addActionListener(a); 
  f.add(b = new Button("Aurevoir"), BorderLayout.SOUTH); 
  b.setActionCommand("Exit"); 
  b.addActionListener(a); 
  f.pack(); 
  f.show(); 
  

 
class MyActionListener implements ActionListener { 
  public void actionPerformed(ActionEvent ae) {
  String s = ae.getActionCommand(); 
  if (s.equals("Exit")) { 
  System.exit(0); 
  
  else if (s.equals("Bonjour")) { 
  System.out.println("Good Morning"); 
  
  else 
  System.out.println(s + " clicked"); 
  
  
2.
Create a Frame in Java
Introduction
This program shows you how to create a frame in java AWT package. The frame in java works like the main window where your components (controls) are added to develop a application. In the Java AWT, top-level windows are represented by the Frame class. Java supports the look and feel and decoration for the frame. For creating java standalone application you must provide GUI to the user.
The most common method of creating a frame is by using single argument constructor of the Frame class that contains the single string argument which is the title of the window or frame. Then you can add user interface by constructing and adding different components to the container one by one.
In this program we are constructing a label to display "Welcome to NMREC COLLEGE." message on the frame. The center alignment of the label has been defined by the Label.CENTER. The frame initially invisible, so after creating the frame it need to visualize the frame by setVisible(true) method.
add(lbl):
This method has been used to add the label to the frame. Method add() adds a component to it's container.
setSize (width, height):
This is the method of the Frame class that sets the size of the frame or window. This method takes two arguments width (int), height (int).
setVisible(boolean):
This is also a method of the Frame class sets the visibility of the frame. The frame will be invisible if you pass the boolean value false otherwise frame will be visible.
Here is the code of the progam : 
import java.awt.*;

public class AwtFrame{
public static void main(String[] args){
Frame frm = new Frame("Java AWT Frame");
Label lbl = new Label("Welcome to NMREC COLLEGE.".",Label.CENTER);
frm.add(lbl);
frm.setSize(400,400);
frm.setVisible(true);
  }
}






3.
How to use KeyListener 
Introduction 
In this section, you will learn how to handle different key events on the Java Awt component by using the event handling in Java. When the given program is executed then you will see the several key events these are applied on the component like the key pressed, key release and so on.
All the key events are handled through the KeyListener Interface that has been implemented in the main class of the program.
Description of this program:
In this program, you will see how to show display the specific massage on the frame according to the event. When you press the key then the message "Key Pressed" will be seen on the frame and if when you stop pressing keys then the message "Key Released" will be seen.
This is possible by using the KeyListener interface. It will generate the KeyEvent and you can the check the exact event by using different method like the keyTyped(), keyPressed() and the keyReleased() method which are used for retrieving the generated specific event.
Here is the code of this program:
import java.awt.*; 
import java.awt.event.*;
 
public class KeyListenerTester extends Frame implements KeyListener{  
  TextField t1;
  Label l1;
  public KeyListenerTester(String s ) {  
  super(s); 
  Panel p =new Panel();
  l1 = new Label ("Key Listener!" ) ;
  p.add(l1);  
  add(p);
  addKeyListener ( this ) ; 
  setSize ( 200,100 );
  setVisible(true);
  addWindowListener(new WindowAdapter(){
 public void windowClosing(WindowEvent e){
  System.exit(0);
 }
  });
  }  
  public void keyTyped ( KeyEvent e ){  
  l1.setText("Key Typed");
 }  
  public void keyPressed ( KeyEvent e){  
  l1.setText ( "Key Pressed" ) ; 
  }  
  public void keyReleased ( KeyEvent e ){  
  l1.setText( "Key Released" ) ; 
  }  
  public static void main (String[]args ){  
  new KeyListenerTester ( "Key Listener Tester" ) ; 
 }  
  }  


4.
Choice Option (Combo) In Java
In this section, you will learn how to create Drop-Down List by using Java AWT package.
Here, you will see in the output of the program that is given ahead for the illustration of the topic. This tells you about the procedure of constructing a drop down list in java by using java awt.
There is a program with complete java code that can be copied and paste in your java application for creating a combo box with some items, has been explained here:
Program Description:
Following program uses the Choice class for creating a Drop-Down List. This program is also using add() method of the Choice class for add item to the list like "ROSE", "INDIA" and "WELCOME".
Choice():- This is the default constructor of Choice class. This creates simply a drop-down list.
Here is the code of this program:
import java.awt.*;
import java.awt.event.*;
public class ChoiceOptionExample{
  public static void main(String[] args) {
  Frame frame=new Frame("Choice");
  Label label=new Label("What is your Choice:");
  Choice choice=new Choice();
  frame.add(label);
  frame.add(choice);
  choice.add("UPPAL");
  choice.add("INDIA");
  choice.add("WELCOME");
  frame.setLayout(new FlowLayout());
  frame.setSize(250,150);
  frame.setVisible(true);
  frame.addWindowListener(new WindowAdapter(){
   public void windowClosing(WindowEvent e){
  System.exit(0);
   }
  });
  }
}


Java AWT Components
Introduction
In this section you will learn about the different components available in the Java AWT package for developing user interface for your program.
Following some components of Java AWT are explained : 
  1. Labels : This is the simplest component of Java Abstract Window Toolkit. This component is generally used to show the text or string in your application and label never perform any type of action. Syntax for defining the label only and with justification :

    Label label_name = new Label ("This is the label text.");
    Above code simply represents the text for the label.
    Label label_name = new Label ("This is the label text.", Label.CENTER);
    Justification of label can be left, right or centered. Above declaration used the center justification of the label using the Label.CENTER
      
  2. Buttons : This is the component of Java Abstract Window Toolkit and is used to trigger actions and other events required for your application. The syntax of defining the button is as follows :

    Button button_name = new Button ("This is the label of the button.");
    You can change the Button's label or get the label's text by using the Button.setLabel(String) and Button.getLabel() method. Buttons are added to the it's container using the add (button_name) method.
      
  3. Check Boxes : This component of Java AWT allows you to create check boxes in your applications. The syntax of the definition of Checkbox is as follows :

    CheckBox checkbox_name = new Checkbox ("Optional check box 1", false);
    Above code constructs the unchecked Checkbox by passing the boolean valued argument false with the Checkbox label through the Checkbox() constructor. Defined Checkbox is added to it's container using add (checkbox_name) method. You can change and get the checkbox's label using the setLabel (String) and getLabel() method. You can also set and get the state of the checkbox using the setState(boolean) and getState() method provided by the Checkbox class.
      
  4. Radio Button : This is the special case of the Checkbox component of Java AWT package. This is used as a group of checkboxes which group name is same. Only one Checkbox from a Checkbox Group can be selected at a time. Syntax for creating radio buttons is as follows :

    CheckboxGroup chkgp = new CheckboxGroup();
    add (new Checkbox ("One", chkgp, false);
    add (new Checkbox ("Two", chkgp, false);
    add (new Checkbox ("Three",chkgp, false);

    In the above code we are making three check boxes with the label "One", "Two" and  "Three". If you mention more than one true valued for checkboxes then your program takes the last true and show the last check box as checked.
      
  5. Text Area: This is the text container component of Java AWT package. The Text Area contains plain text. TextArea can be declared as follows:

    TextArea txtArea_name = new TextArea();
    You can make the Text Area editable or not using the setEditable (boolean) method. If you pass the boolean valued argument false then the text area will be non-editable otherwise it will be editable. The text area is by default in editable mode. Text are set in the text area using the setText(string) method of the TextArea class.
     
  6. Text Field: This is also the text container component of Java AWT package. This component contains single line and limited text information. This is declared as follows :

    TextField txtfield = new TextField(20);
    You can fix the number of columns in the text field by specifying the number in the constructor. In the above code we have fixed the number of columns to 20.

Different types of event in Java AWT  
There are many types of events that are generated by your AWT Application. These events are used to make the application more effective and efficient. Generally, there are twelve types of event are used in Java AWT. These are as follows : 
  1. ActionEvent
  2. AdjustmentEvent
  3. ComponentEvent
  4. ContainerEvent
  5. FocusEvent
  6. InputEvent
  7. ItemEvent
  8. KeyEvent
  9. MouseEvent
  10. PaintEvent
  11. TextEvent
  12. WindowEvent
These are twelve mentioned events are explained as follows : 
  1. ActionEvent: This is the ActionEvent class extends from the AWTEvent class. It indicates the component-defined events occurred i.e. the event generated by the component like Button, Checkboxes etc. The generated event is passed to every EventListener objects that receives such types of events using the addActionListener() method of the object.
     
  2. AdjustmentEvent: This is the AdjustmentEvent class extends from the AWTEvent class. When the Adjustable Value is changed then the event is generated.
     
  3. ComponentEvent: ComponentEvent class also extends from the AWTEvent class. This class creates the low-level event which indicates if the object moved, changed and it's states (visibility of the object). This class only performs the notification about the state of the object. The ComponentEvent class performs like root class for other component-level events.
      
  4. ContainerEvent: The ContainerEvent class extends from the ComponentEvent class. This is a  low-level event which is generated when container's contents changes  because of addition or removal of a components.
     
  5. FocusEvent: The FocusEvent class also extends from the ComponentEvent class. This class indicates about the focus where the focus has gained or lost by the object. The generated event is passed to every objects that is registered to receive such type of events using the addFocusListener() method of the object.
     
  6. InputEvent: The InputEvent class also extends from the ComponentEvent class. This event class handles all the component-level input events. This class acts as a root class for all component-level input events.
     
  7. ItemEvent: The ItemEvent class extends from the AWTEvent class. The ItemEvent class handles all the indication about the selection of the object i.e. whether selected or not. The generated event is passed to every ItemListener objects that is registered to receive such types of event using the addItemListener() method of the object.
     
  8. KeyEvent: KeyEvent class extends from the InputEvent class. The KeyEvent class handles all the indication related to the key operation in the application if you press any key for any purposes of the object then the generated event gives the information about the pressed key. This type of events check whether the pressed key left key or right key, 'A' or 'a' etc.
     
  9. MouseEvent: MouseEvent class also extends from the InputEvent class. The MouseEvent class handle all events generated during the mouse operation for the object. That contains the information whether mouse is clicked or not if clicked then checks the pressed key is left or right.
     
  10. PaintEvent: PaintEvent class also extends from the ComponentEvent class. The PaintEvent class only ensures that the paint() or update() are serialized along with the other events delivered from the event queue.
      
  11. TextEvent: TextEvent class extends from the AWTEvent class. TextEvent is generated when the text of the object is changed. The generated events are passed to every TextListener object which is registered to receive such type of events using the addTextListener() method of the object.
     
  12. WindowEvent : WindowEvent class extends from the ComponentEvent class. If the window or the frame of  your application is changed (Opened, closed, activated, deactivated or any other events are generated), WindowEvent is generated.

Events    
In this section, you will learn how to handle events in Java awt. Events are the integral part of the java platform. You can see the concepts related to the event handling through the example and use methods through which you can implement the event driven application.
For any event to occur, the objects registers themselves as listeners. No event takes place if there is no listener i.e. nothing happens when an event takes place if there is no listener. No matter how many listeners there are, each and every listener is capable of processing an event. For example, a SimpleButtonEvent applet registers itself as the listener for the button's action events that creates a Button instance.
ActionListener can be implemented by any Class including Applet. One point to remember here is that all the listeners are always notified. Moreover, you can also call AWTEvent.consume() method whenever you don't want an event to be processed further. There is another method which is used by a listener to check for the consumption. The method is isConsumed() method. The processing of the events gets stopped with the consumption of the events by the system once a listener is notified. Consumption only works for InputEvent and its subclasses. Moreover, if you don't want any input from the user through keyboard then you can use consume() method for the KeyEvent. 
The step by step procedure of Event handling is as follow:
  1. When anything interesting happens then the subclasses of AWTEvent are generated by the component.
  2. Any class can act like a Listener class permitted by the Event sources. For example, addActionListener() method is used for any action to be performed, where Action is the event type. There is another method by which you can remove the listener class which is removeXXXListener() method, where XXX is the event type. 
  3. A listener type has to be implemented for an event handling such as ActionListener.
  4. There are some special type of listener types as well for which you need to implement multiple methods like key Events. There are three methods which are required to be implemented for Key events and to register them i.e. one for key release, key typed and one for key press. There are some special classes as well which are known as adapters that are used to implement the listener interfaces and stub out all the methods. these adapter classes can be sub classed and and can override the necessary method. 
AWTEvent
Most of the times every event-type has Listener interface as Events subclass the AWTEvent class. However, PaintEvent and InputEvent don't have the Listener interface because only the paint() method can be overriden with PaintEvent etc.
Low-level Events
A low-level input or window operation is represented by the Low-level events. Types of Low-level events are mouse movement, window opening, a key press etc. For example, three events are generated by typing the letter 'A' on the Keyboard one for releasing, one for pressing, and one for typing. The different type of low-level events and operations that generate each event are show below in the form of a table.
 FocusEvent 
 Used for Getting/losing focus.
 MouseEvent 
 Used for entering, exiting, clicking, dragging, moving, pressing, or releasing.
 ContainerEvent 
 Used for Adding/removing component.
 KeyEvent 
 Used for releasing, pressing, or typing (both) a key.
 WindowEvent 
 Used for opening, deactivating, closing, Iconifying, deiconifying, really closed.
 ComponentEvent 
 Used for moving, resizing, hiding, showing.
Semantic Events
The interaction with GUI component is represented by the Semantic events like changing the text of a text field, selecting a button etcThe different events generated by different components is shown below.
 ItemEvent
 Used for state changed.
 ActionEvent 
 Used for do the command.
 TextEvent 
 Used for text changed.
AdjustmentEvent 
 Used for value adjusted.
Event Sources
If a component is an event source for something then the same happens with its subclasses. The different event sources are represented by the following table.
 Low-Level Events
 Window 
 WindowListener
 Container 
 ContainerListener
 Component 
 ComponentListener
 FocusListener
 KeyListener
 MouseListener
 MouseMotionListener

 Semantic Events
  Scrollbar 
  AdjustmentListener
 TextArea
 TextField
  TextListener
 Button
 List
 MenuItem
 TextField 
 ActionListener
 Choice
 Checkbox
 Checkbox
 CheckboxMenuItem
 List 
 ItemListener
Event Listeners

Every listener interface has at least one event type. Moreover, it also contains a method for each type of event the event class incorporates. For example as discussed earlier, the KeyListener has three methods, one for each type of event that the KeyEvent has: keyTyped(), keyPressed(), and keyReleased().
The Listener interfaces and their methods are as follow:
 Interface
 Methods
 WindowListener 
 windowActivated(WindowEvent e)
 windowDeiconified(WindowEvent e)
 windowOpened(WindowEvent e)
 windowClosed(WindowEvent e) 
 windowClosing(WindowEvent e)
 windowIconified(WindowEvent e)
 windowDeactivated(WindowEvent e)
 ActionListener
 actionPerformed(ActionEvent e)
 AdjustmentListener
 adjustmentValueChanged(AdjustmentEvent e)
 MouseListener
 mouseClicked(MouseEvent e)
 mouseEntered(MouseEvent e)
 mouseExited(MouseEvent e)
 mousePressed(MouseEvent e)
 mouseReleased(MouseEvent e)
 FocusListener
 focusGained(FocusEvent e)
 focusLost(FocusEvent e)
 ItemListener
 itemStateChanged(ItemEvent e)
 KeyListener
 keyReleased(KeyEvent e)
 keyTyped(KeyEvent e)

 keyPressed(KeyEvent e)
 ComponentListener
 componentHidden(ComponentEvent e)
 componentMoved(ComponentEvent e)
 componentShown(ComponentEvent e)
 componentResized(ComponentEvent e)
 MouseMotionListener
 mouseMoved(MouseEvent e)

 mouseDragged(MouseEvent e)
 TextListener
 textValueChanged(TextEvent e)
 ContainerListen er
 componentAdded(ContainerEvent e)

 componentRemoved(ContainerEvent e)

Handling Focus Changes in Java
Introduction
In this section, you will learn about handling the focus changes in java. This section shows you how the event be handled according to the focuses and to find out whether the component got the focus or lost the focus.  
This program determines the focus changes events. You can set the different-different events for the focused of the several components particularly. The generated focus events are performed by the FocusListener of the object used in your application using the addFocusListener() method. The generated event (FocusEvent) is passed to every FocusListener objects that receives such types of events using the addFocusListener() method of the object. The addFocusListener() method is takes the instance of MyFcousListener class.
MyFocusListener:
This is the inner class used in the FocusChange class in which, the focusGained() method has been used to receive the generated event. This method sets the text of the source of the event to the label component. This program displays the three command buttons on the frame. If you select any button of those then the text of that button will be shown on the label.
FocusAdapter:
This is the abstract class is used to receive the keyboard focus event. 
Here is the code of program:
import java.awt.*;
import java.awt.event.*;

public class FocusChange{
  Label label;
  public static void main(String[] args){
  FocusChange fc = new FocusChange();
  }

  public FocusChange(){
  Frame frame = new Frame("RoseIndia.Net");
  Panel panel = new Panel();
  Button yes = new Button("Yes");
  Button no = new Button("No");
  Button cancel = new Button("Cancel");
  yes.addFocusListener(new MyFocusListener());
  no.addFocusListener(new MyFocusListener());
  cancel.addFocusListener(new MyFocusListener());
  panel.add(yes);
  panel.add(no);
  panel.add(cancel);
  frame.add(panel,BorderLayout.NORTH);
  label = new Label();
  frame.add(label,BorderLayout.CENTER);
  frame.setSize(400,400);
  frame.setVisible(true);
  frame.addWindowListener(new WindowAdapter(){
  public void windowClosing(WindowEvent we){
  System.exit(0);
  }
  });
  }

  public class MyFocusListener extends FocusAdapter{
  public void focusGained(FocusEvent fe){
  Button bt = (Button)fe.getSource();
  String str = bt.getLabel();
  label.setText(str);
  }
  }
}

BorderLayout Example In java
Introduction
In this section, you will learn how to create BorderLayout in java awt package. The Border Layout is arranging and resizing components to set in five position which is used in this program. The java program uses and declares all positions as a  NORTH, SOUTH, WEST, EAST, and
CENTER. Here, you will understand about this position how to use in this program.
Program Description:
Following program uses the BorderLayout class for creating Button and set on the frame. Here, define the class named BorderLayoutExample for using  this program. This Java Application uses BorderLayout for setting the position on the frame.
BorderLayout(): This is default constructors of the class Border layout class. This class constructs a new border layout without any gaps between components.  
Here is the code of this program:
import java.awt.*;
import java.awt.event.*;

public class BorderLayoutExample {

  public static void main(String[] args) {
  Frame frame= new Frame("BorderLayout Frame");
  Panel pa= new Panel();
  Button ba1= new Button();
  Button ba2=new Button();
  Button ba3=new Button();
  Button ba4=new Button();
  Button ba5=new Button();
  frame.add(pa);
  pa.setLayout(new BorderLayout());
  pa.add(new Button("Wel"), BorderLayout.NORTH);
  pa.add(new Button("Come"), BorderLayout.SOUTH);
  pa.add(new Button("Rose"), BorderLayout.EAST);
  pa.add(new Button("India"), BorderLayout.WEST);
  pa.add(new Button("RoseIndia"), BorderLayout.CENTER);
  frame.setSize(300,300);
  frame.setVisible(true);
  frame.addWindowListener(new WindowAdapter(){
  public void windowClosing(WindowEvent e){
  System.exit(0);
  }
  });
  }  
}


Java - Drawing Shapes Example in java
Applet is a program to run on the browser and it is embedded on the web page. This program is not system level program but it is a network level program. The Applet class is a super class  of any applet.  Applet viewer is used to view or test the applet whether the applet is running properly or not.

In this program we will see how to draw the different types of shapes like line, circle and rectangle. There are different types of methods for the Graphics class of the java.awt.*; package have been used to draw the appropriate shape. Explanation of the methods used in the program is given just ahead : 
Graphics.drawLine() :
The drawLine() method has been used in the program to draw the line in the applet. Here is the syntax for the drawLine() method :

drawLine(int X_from_coordinate, int Y_from_coordinate, int X_to_coordinate, int Y_to_coordinate);
Graphics.drawString() :
The drawSring() method draws the given string as the parameter. Here is the syntax of the drawString() method :

drawString(String string, int X_coordinate, int Y_coordinate);

Graphics.
drawOval() :
The drawOval() method draws the circle. Here is the syntax of the drawOval() method :

g.drawOval(int X_coordinate, int Y_coordinate, int Wdth, int height);
Graphics.drawRect() :
The drawRect() method draws the rectangle. Here is the syntax of the drawRect() method : 
g.drawRect(int X_coordinate, int Y_coordinate, int Wdth, int height)

Here is the java code of the program :.
import java.applet.*;
import java.awt.*;

public class  CircleLine extends Applet{
  int x=300,y=100,r=50;

  public void paint(Graphics g){
  g.drawLine(3,300,200,10);
  g.drawString("Line",100,100);
  g.drawOval(x-r,y-r,100,100);
  g.drawString("Circle",275,100);
  g.drawRect(400,50,200,100);
  g.drawString("Rectangel",450,100);
  }
}
Here is the HTML code of the program:
<HTML>
<HEAD>
</HEAD>
<BODY>
<div align="center">
<APPLET CODE="CircleLine.class" WIDTH="800" HEIGHT="500"></APPLET>
</div>
</BODY>
</HTML>















No comments:

Post a Comment