The MouseWheelEvent in java programming

Friday 23 November 2012
An event which indicates that the mouse wheel was rotated in a component.
A wheel mouse is a mouse which has a wheel in place of the middle button. This wheel can be rotated towards or away from the user. Mouse wheels are most often used for scrolling, though other uses are possible.
A MouseWheelEvent object is passed to every MouseWheelListener object which registered to receive the "interesting" mouse events using the component's addMouseWheelListener method. Each such listener object gets a MouseEvent containing the mouse event.

MouseWheelEvent

public MouseWheelEvent(Component source,int id,long when, int modifiers, int x,
                      int y, int clickCount, boolean popupTrigger,int scrollType,
                       int scrollAmount,int wheelRotation)
 
 
Constructs a MouseWheelEvent object with the specified source component, type, modifiers, coordinates, scroll type, scroll amount, and wheel rotation. Note that passing in an invalid id results in unspecified behavior.

source - the Component that originated the event



when - a long that gives the time the event occurred
modifiers - the modifier keys down during event (shift, ctrl, alt, meta)
x - the horizontal x coordinate for the mouse location
y - the vertical y coordinate for the mouse location
clickCount - the number of mouse clicks associated with event
popupTrigger - a boolean, true if this event is a trigger for a popup-menu
scrollType - the type of scrolling which should take place in response to this event; valid values are WHEEL_UNIT_SCROLL and WHEEL_BLOCK_SCROLL
scrollAmount - for scrollType WHEEL_UNIT_SCROLL, the number of units to be scrolled
wheelRotation - the amount that the mouse wheel was rotated (the number of "clicks")

getScrollType

public int getScrollType()
 
Returns the type of scrolling that should take place in response to this event. This is determined by the native platform. Legal values are:
  • MouseWheelEvent.WHEEL_UNIT_SCROLL
  • MouseWheelEvent.WHEEL_BLOCK_SCROLL 

getScrollAmount

public int getScrollAmount()
 
Returns the number of units that should be scrolled in response to this event. Only valid if getScrollType returns MouseWheelEvent.WHEEL_UNIT_SCROLL

getWheelRotation

public int getWheelRotation()
Returns the number of "clicks" the mouse wheel was rotated.
Returns:
negative values if the mouse wheel was rotated up/away from the user, and positive values if the mouse wheel was rotated down/ towards the user

getUnitsToScroll

public int getUnitsToScroll()
This is a convenience method to aid in the implementation of the common-case MouseWheelListener - to scroll a ScrollPane or JScrollPane by an amount which conforms to the platform settings. (Note, however, that ScrollPane and JScrollPane already have this functionality built in.) This method returns the number of units to scroll when scroll type is MouseWheelEvent.WHEEL_UNIT_SCROLL, and should only be called if getScrollType returns MouseWheelEvent.WHEEL_UNIT_SCROLL.
Direction of scroll, amount of wheel movement, and platform settings for wheel scrolling are all accounted for. This method does not and cannot take into account value of the Adjustable/Scrollable unit increment, as this will vary among scrolling components.
A simplified example of how this method might be used in a listener:
 
  mouseWheelMoved(MouseWheelEvent event) {
      ScrollPane sp = getScrollPaneFromSomewhere(); 
      Adjustable adj = sp.getVAdjustable()
      if (MouseWheelEvent.getScrollType() == WHEEL_UNIT_SCROLL) {
          int totalScrollAmount =
              event.getUnitsToScroll() *
              adj.getUnitIncrement();
          adj.setValue(adj.getValue() + totalScrollAmount);
      }
  }
 

The MouseEvent class in java programming

An event which indicates that a mouse action occurred in a component. A mouse action is considered to occur in a particular component if and only if the mouse cursor is over the unobscured part of the component's bounds when the action happens. Component bounds can be obscurred by the visible component's children or by a menu or by a top-level window. This event is used both for mouse events (click, enter, exit) and mouse motion events (moves and drags).


  MOUSE_CLICKED
The mouse clicked event type.
public static final int MOUSE_CLICKED
 
 
  MOUSE_DRAGGED
The mouse dragged event type.
public static final int MOUSE_DRAGGED
 
 
  MOUSE_ENTERED
The mouse entered event type.
public static final int MOUSE_ENTERED
 
 
  MOUSE_EXITED
The mouse exited event type.
public static final int MOUSE_EXITED
 
  MOUSE_FIRST
Marks the first integer id for the range of mouse event ids.
public static final int MOUSE_FIRST
 
  MOUSE_LAST
Marks the last integer id for the range of mouse event ids.
public static final int MOUSE_LAST
 
  MOUSE_MOVED
The mouse moved event type.
public static final int MOUSE_MOVED
 
  MOUSE_PRESSED
The mouse pressed event type.
public static final int MOUSE_PRESSED
 
  MOUSE_RELEASED
The mouse released event type.
public static final int MOUSE_RELEASED 
 
MOUSE_WHEEL
       The "mouse wheel" event. This is the only MouseWheelEvent. It occurs when a mouse equipped with a wheel has its wheel rotated.
      public static final int MOUSE_WHEEL

Important Classes and Interfaces

These classes and interfaces are defined in java.awt.event. The first three are the most commonly used.
MouseEventA MouseEvent object is passed to all mouse listeners. The most useful information in a MouseEvent is the x and y coordinates of the mouse cursor.
MouseListenerInterface for mouse presses, releases, clicks, enters, and exits.
MouseMotionListenerInterface for mouse moves and drags.
MouseInputListenerInterface combination of MouseListener and MouseMotionListener.

MouseAdapterClass useful for writing anonymous listener for mouse button presses, entering, ...
MouseMotionAdapterClass useful for writing anonymous listener for mouse movement.
Handling the mouse wheel.
MouseWheelEvent Object passed to mouseWheelMoved. Subclass of MouseEvent.
MouseWheelListenerInterface to handle wheel movements. Write mouseWheelMoved(MouseWheelEvent we)


Constructor Detail

public MouseEvent(Component source,int id,long when,int modifiers,int x,int y,
                   int clickCount,boolean popupTrigger,int button)
 
source - the Component that originated the event
id - the integer that identifies the event
when - a long int that gives the time the event occurred
modifiers - the modifier keys down during event (e.g. shift, ctr l, alt, meta) Either extended _DOWN_MASK or old _MASK modifiers should be used, but both models should not be mixed in one event. Use of the extended modifiers is preferred.
x - the horizontal x coordinate for the mouse location
y - the vertical y coordinate for the mouse location
clickCount - the number of mouse clicks associated with event
popupTrigger - a boolean, true if this event is a trigger for a popup menu
button - which of the mouse buttons has changed state. NOBUTTON, BUTTON1, BUTTON2 or BUTTON3.
 
 Method Detail

    getX
     public int getX()
Returns the x position of the event relative to the source component.
  getY
    public int getY()
Returns the y position of the event relative to the source component.
  getPoint
    public Point getPoint()
Returns the x,y position of the event relative to the source component.
  translatePoint
     public synchronized void translatePoint(int x,
                                         int y)
Translates the coordinate position of the event by x, y.
Parameters:
x - the x value added to the current x coordinate position
y - the y value added to the current y coordinate position
  getClickCount
      public int getClickCount()
Return the number of mouse clicks associated with this event.
  isPopupTrigger
      public boolean isPopupTrigger()
Returns whether or not this mouse event is the popup-menu trigger event for the platform.
  paramString
     public String paramString()
Overrides:
paramString in class ComponentEvent

Java Frame Drag and drop example program

Wednesday 21 November 2012
Dragging requires more physical effort than moving the same pointing device without holding down any buttons. Because of this, a user cannot move as quickly and precisely while dragging. However, drag-and-drop operations have the advantage of thoughtfully chunking together two operands (the object to drag, and the drop location) into a single action. Extended dragging and dropping (as in graphic design) can stress the mousing hand. A design problem appears when the same button selects and drags items. Imprecise movement can cause a dragging when the user just wants to select. Here the JFrame will be used for drag and drop



import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class dragdemoex
{
  public static void main(String[] args)
    {
    JFrame frame = new JFrame("Drag and Drop Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new JPanel());
    JTextField textField = new JTextField(25);
    textField.setText("http://codercheck.blogspot.com/");
    frame.add(textField);

    JTextArea textArea = new JTextArea(4, 25);
    textArea.setText("Demonstrating\ndrag and drop");
    frame.getContentPane().add(new JScrollPane(textArea));
    textArea.setDragEnabled(true);
    textField.setDragEnabled(true);
    frame.pack();
    frame.setVisible(true);

   }
}
Output 




java code for reading input from console


import java.io.Console;
public class MainClass
{
  public static void main(String[] args) throws ClassNotFoundException
   {
    Console console = System.console();
    if (console == null)
  {
      System.err.println("sales: unable to obtain console");
      return;
    }

    String username = console.readLine("Enter username: ");
    System.out.println(username);
  }
}


We can read Java’s input from “System.in” console, there are two common ways to read input from console.

1) InputStreamReader wrapped in a BufferedReader
2) Scanner classes in JDK1.5

Output


C:\pgm\console>java MainClass
 Enter username: vineeth
vineeth


Here is the java program for read string from console application.

Masking password input from the console : Java


import java.io.Console;
import java.util.Arrays;

public class ConsoleMain
 {

  public static void main(String[] args)
 {
    Console console = System.console();
    String username = console.readLine("Username: ");
    char[] password = console.readPassword("Password: ");

    if (username.equals("vineeth") && String.valueOf(password).equals("vineeth"))
  {
      console.printf("Welcome to Java Application %1$s.\n", username);

      Arrays.fill(password, ' ');
    } else {
      console.printf("Invalid username or password.\n");
    }
  }
}




The idea here is that you can call Arrays. fill (or equivalent) to "blank" the char array as soon as you've validated the password, and from that point the password is no longer stored in memory.
 Since Strings are immutable, the String will remain in the heap until it is garbage collected - which if it manages to get itself interned will be never, and in any other case could still be "too long". All the while it is there, it's potentially vulnerable to sniffing from a variety of vectors.The Console object supports secure password entry through its readPassword method. This method helps secure password entry in two ways. First, it suppresses echoing, so the password is not visible on the user's screen. Second, readPassword returns a character array, not a String, so the password can be overwritten, removing it from memory as soon as it is no longer needed.

The keyEvent class in java Programming

Saturday 17 November 2012
A key event is generated when keyboard input occurs.There are three types of key events ,which are identified by these integer constant

KEY_FIRST
Marks the first integer id for the range of key event ids.
KEY_LAST
Marks the last integer id for the range of key event ids.
KEY_PRESSED
The key pressed event type.
KEY_RELEASED
The key released event type.
KEY_TYPED
The key typed event type.

 

Constructor in KeyEvent

KeyEvent(Component, int, long, int, int)

public KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar)
Constructs a KeyEvent object with the specified source component, type, modifiers, and key.
Parameters: source - the object where the event originated

KeyEvent(Component, int, long, int, int, char) 

Constructs a KeyEvent object with the specified source component, type, modifiers, and key.
public KeyEvent(Component source,int id,long when, int modifiers, int keyCode)

KeyEvent Method

getKeyChar()
Returns the character associated with the key in this event.
getKeyCode()
Returns the integer key-code associated with the key in this event.
getKeyModifiersText(int)
Returns a String describing the modifier key(s), such as "Shift", or "Ctrl+Shift".
getKeyText(int)
Returns a String describing the keyCode, such as "HOME", "F1" or "A". isActionKey() Returns whether or not the key in this event is an "action" key, as defined in Event.java.
paramString()
setKeyChar(char)
setKeyCode(int)
setModifiers(int)


CHAR_UNDEFINED,KEY_PRESSED and KEY_RELEASED events which do not map to a valid

Unicode character do not have a defined keyChar.


VK_0
VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39)
VK_1
VK_2
VK_3
VK_4
VK_5
VK_6
VK_7
VK_8
VK_9

VK_A
VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A)
VK_ACCEPT
VK_ADD
VK_ALT
VK_B
VK_BACK_QUOTE
VK_BACK_SLASH
VK_BACK_SPACE
VK_C
VK_CANCEL
VK_CAPS_LOCK
VK_CLEAR
VK_CLOSE_BRACKET
VK_COMMA
VK_CONTROL
VK_CONVERT
VK_D
VK_DECIMAL
VK_DELETE
VK_DIVIDE
VK_DOWN
VK_E
VK_END
VK_ENTER

The ItemEvent class in java programming

An itemEvent is generated when a check or a list item is clicked or when a check able menu item is selected or deselected .There are two types of item events,which are identified by the following integer

DESELECTED
the user deselected an item

SELECTED 
the use selected an item

in addition ItemEvent defines one integer constant ITEM_STATE_CHANGED that signifies a change of state

ItemEvent has this constructor

ItemEvent(ItemSelectable src,int type,Object entry,int state)






getItem()


The getItem() method can be used to obtain a reference to the item that generated an event .Its signature is show here

Object getItem()

getItemSelectable()

The getItemSelectable() method can be used to obtain a reference to the ItemSelectable object that generated an event

ItemSelectable getItemSelectable()

getStateChange()

The getStateChange() method returns the satechange for the event

int getStateChange()

The InputEvent class in java programming

Friday 16 November 2012
InputEvent defines several integer constants that represent any modifiers ,such as the control key pressed ,that might be associated with the event .originally the InputEvent class defined the following modifiers

ACTION_EVENT_MASK INPUT_METHOD_EVENT_MASK
ADJUSTMENT_EVENT_MASK, INVOCATION_EVENT_MASK
MOUSE_MOTION_EVENT_MASK MOUSE_EVENT_MASK
COMPONENT_EVENT_MASK ITEM_EVENT_MASK
CONTAINER_EVENT_MASK WINDOW_FOCUS_EVENT_MASK
FOCUS_EVENT_MASK WINDOW_STATE_EVENT_MASK
HIERARCHY_BOUNDS_EVENT_MASK WINDOW_EVENT_MASK
PAINT_EVENT_MASK, RESERVED_ID_MAX MOUSE_WHEEL_EVENT_MASK
KEY_EVENT_MASK TEXT_EVENT_MASK
HIERARCHY_EVENT_MASK


Method Summary
 void consume()
          Consumes this event so that it will not be processed in the default manner by the source which originated it.
 int getModifiers()
          Returns the modifier mask for this event.
 int getModifiersEx()
          Returns the extended modifier mask for this event.
static String getModifiersExText(int modifiers)
          Returns a String describing the extended modifier keys and mouse buttons, such as "Shift", "Button1", or "Ctrl+Shift".
 long getWhen()
          Returns the timestamp of when this event occurred.
 boolean isAltDown()
          Returns whether or not the Alt modifier is down on this event.
 boolean isAltGraphDown()
          Returns whether or not the AltGraph modifier is down on this event.
 boolean isConsumed()
          Returns whether or not this event has been consumed.
 boolean isControlDown()
          Returns whether or not the Control modifier is down on this event.
 boolean isMetaDown()
          Returns whether or not the Meta modifier is down on this event.
 boolean isShiftDown()
          Returns whether or not the Shift modifier is down on this event.

The FocusEvent class in java programming

The component-level focus event. There are two levels of focus change events: permanent and temporary. Permanent focus change events occur when focus is directly moved from one component to another, such as through calls to requestFocus() or as the user uses the Tab key to traverse components. Temporary focus change events occur when focus is temporarily gained or lost for a component as the indirect result of another operation, such as window deactivation or a scroll bar drag. In this case, the original focus state will automatically be restored once that operation is finished, or, for the case of window deactivation, when the window is reactivated. Both permanent and temporary focus events are delivered using the FOCUS_GAINED and FOCUS_LOST event ids; the levels may be distinguished in the event using the isTemporary() method

FocusEvent(Component, int)

Constructs a permanent-level FocusEvent object with the specified source component and type.

sssssFocusEvent(Component, int, boolean)


Constructs a FocusEvent object with the specified source component, type, and whether or not the focus event is a temporary level event.

Method Detail

isTemporary

public boolean isTemporary()
Identifies the focus change event as temporary or permanent.
Returns:
true if the focus change is temporary; false otherwise

getOppositeComponent

public Component getOppositeComponent()
 
Returns the other Component involved in this focus change.
 For a FOCUS_GAINED event, this is the Component that lost focus. For a
FOCUS_LOST event, this is the Component that gained focus. 
If this focus change occurs with a native application, with a Java application
in a different VM or context, or with no other Component, then null is
returned.

Returns:
the other Component involved in the focus change, or null

paramString

public String paramString()
Returns a parameter string identifying this event. This method is useful for event-logging and for debugging.
Overrides:
paramString in class ComponentEvent
Returns:
a string identifying the event and its attributes


The Container class in java programming

A ContainerEvent is generated when a component is added to or removed from a container.There are two typed of container events.The ContainerEvent class defines int constants that can be used to identify the COMPONENT_ADDED and COMPONENT_REMOVED .They indicate that a component has been added to or  removed from the container.


Container Event is a subclass of component Event and has this constructor


ContainerEvent(Component src,int type,Component comp)



here src is a reference to the container that generated this event.The type of the event is specified by type and the component that has been added to removed from the container is comp


Container geContainer()

Component getChild()

The ComponentEvent class in java Programming


A ComponentEvent  is generated when the size ,position or visibility of a component is changed .There are four types of component events.The ComponentEvent class defines integer constants that can be used to identity them.The constants and their meaning are shown here

COMPONENT_HIDDEN -The component was hidden

COMPONENT_MOVED -The component was moved

COMPONENT_RESIZED -The component was re sized

COMPONENT_SHOWN - The component became visible


ComponentEvent has this constructor

ComponentEvent(Component src,int type)

here src is a reference to the object that generated this event.The type of the events is specified by type
ComponentEvent is the supercladd either directly or indirectly of ContainerEvent ,FocusEvent,KeyEvent,MouseEvent and WindowEvent

getcomponent()

The method returns the component that generated the event .


The AdjustmentEvent class in java programming


An AdjustmentEvent  is generated by a scroll bar.There are five types of adjustment events .The AdjustmentEvent  class defines integer constants that can be used to identity them,The constants and their meanings are shown

BLOCK_DECREMENT  -The user clicked inside the scroll bar to decrease its value
BLOCK_INCREMENT -The user clicked inside the scroll bar to increase its value
TRACK  -The slider was dragged
UNIT_DECREMENT -The button at the end of the scroll bar was clicked to decrease its value.
UNIT_INCREMENT -The button at the end of the scroll bar was clicked to increase its value


In addition there is an integer constant ADJUSTMENT_VALUE_CHANGED, that indicates that a change has occurred

AdjustmentEvent(adjustable src,int id,int type,int data)

Adjustable getAdjustable()

The geAdjustable() method returns the object that generated the event

int getAdjustmentType()

The type of the adjustmewnt event may be obtained by the getAdjustmentType() method.it returns one of the constants defined by AdjustmentEvent

int getValue()

 the amount of the adjustment can be obtained from the getValue() method

Action Event class in java Programming


An ActionEvent is generated when a button is pressed ,a lis item is double clicked or menu item is selected .The Action Event class defines four integer constants that can be used to identity any modifiers associated with an action event ALT_MASK ,CTRL_MASK,META_MASK and SHIFT_MASK.In addition there is an integer constant ACTION_PERFORMED which can be to identity action events

ActionEvent has these three constructors


ActionEvent(Object src,int type,String cmd)
ActionEvent(Object src,int type,String cmd,int modifiers)
ActionEvent(Object src,int type,String cmd,long when,int modifiers)


src is a reference to the object that generated this event .the type of the specified by Type ,and its command string is cmd,the argument modifiers indicates which modifiers key(ALT,CTRL,META,SHIFT) were pressed when the event was generated .The when parameter specifies when the event occurred.

getActionCommand()

When a button is pressed an action event is generated that has a command name equal to the label on that button

getModifiers()

The getModifiers() method returns a value that indicates which modifiers keys(ALT(CTRL,META,SHIFT) were pressed when the event was generated .

getWhen()

The getWhen() that returns the time at which the event took place.This is called the event's timestamps.


Event class and event listener in java programming

This classes that represent events are at the core of java'sevent hanflimg mechanism.This we begin our study of eventhandling with a tour of the events classes .As you will see ,thet provide a consistent easy to use means of encapsulating events ,At the root of the java events c;ass hierachy is Eventobject ,Which in java.util .It is the super class for all events .

Object getSource()
This method is defined in the Event Object class. It returns the object that originated the event. So if the user has clicked a Push button, the method getSource returns the object corresponding to Push button is generated.
int getID()
This method returns the integer value corresponding to the type of event. For example if the user has clicked on the mouse, the method getID returns the integer defined as MouseEvent.MOUSE_CLICKED.
AWT event classes 
The subclasses of ATW Event can be categorized into two groups - Semantic events and low-level events. Semantic events directly correspond to high level user interactions with a GUI component. Clicking of a button is an example of a semantic event. Following event classes are semantic classes.
ActionEvent
AdjustmentEvent
ItemEvent
TextEvent 
 
Multiple low-level events may get generated for each high level user event. Following event classes are low level event classes.

ComponentEvent
ContainerEvent
FocusEvent
KeyEvent
MouseEvent
PaintEvent
WindowEvent

AdjustmentEvent is generated when the user adjusts the position of a scrollbar. Scrollbar is the only GUI control that receives the AdjustmentEvent.


ItemEvent is generated when an item is selected or deselected. Following components generate ItemEvents.
CheckBox : When the state of the CheckBox is changed.
CheckBoxMenuItem : When the state of a MenuItem is changed.
Choice : When the state of a ChoiceBox is changed.
List : When an item in list is selected or deselected.

TextEvent is generated when the contents of text component are changed. The components that generate TextEvent are TextArea and TextField.
Now I will describe the GUI components corresponding to low level event classes.
FocusEvent : This event is generated when a component gains or looses focus. Focus may be gained by bringing the mouse over a component (or by using the tab key). The component that has the focus receives all user keyboard events. Focus events are generated by objects of Component class and all its subclasses.

KeyEvent and MouseEvent are subclasses of abstract InputEvent class. Both these events are generated by objects of type Component class and its subclasses. The KeyEvent is generated when the user presses or releases a key on the keyboard. The MouseEvent is generated when the user presses the mouse or moves the mouse.

WindowEvent are generated for the Window class and its subclasses. These events are generated if an operation is performed on a window. The operation could be closing of window, opening of window, activating a window etc.

PaintEvent is generated when a component needs to be repainted (for example when an application which is in front is closed and the component needs to be redrawn.) PaintEvents are internally handled by AWT, and cannot (and should not) be handled by you in the application.

ComponentEvent are also generated by objects of type Component class and its subclasses. This event is generated when a component is hidden, shown, moved or resized.

ContainerEvents are generated when a component is added or removed from a container. ComponentEvent and ContainerEvent are handled by AWT and are not normally handled by the user.


Table Event types and corresponding EventSource & EventListener
Event Type Event Source Event Listener interface
ActionEvent Button, List, MenuItem, TextField ActionListener
AdjustmentEvent Scrollbar AdjustmentListener
ItemEvent Choice, Checkbox, CheckboxMenuItem, List ItemListener
TextEvent TextArea, TextField TextListener
ComponentEvent Component ComponentListener
ContainerEvent Container ContainerListener
FocusEvent Component FocusListener
KeyEvent Component KeyListener
MouseEvent Component MouseListener, MouseMotionListener
WindowEvent Window WindowListener


A listener is an object that is notified when an event occur .It has two major requirements .First it must have been registerd with one or meore source to recieve notifications about specific types of events .Second it must implemented methods to recieve and process thes notifications .The methods that recieves and process events are defied in a set of interdaces found in java.awt.event .For example the MouseMotionListener interface defines two methods to recieve notifications whenthe mouse is dragged or moved .Any object may recieve and process notifications when the mouse is dragged or moved .Any object may recieve and process one or both of these events if it provides n implementation of this interface .


Table Event Listener Interfaces and corresponding methods which it defines
Event Listener interface Event Listener Methods
ActionListener actionPerformed(ActionEvent evt)
AdjustmentListener adjustmentValueChanged(AjustmentEvent evt)
ItemListener itemStateChanged(ItemEvent evt)
TextListener textValueChanged(TextEvent evt)
ComponentListener componentHidden(ComponentEvent evt), componentMoved(ComponentEvent evt), componentResized(ComponentEvent evt), componentShown(ComponentEvent evt)
ContainerListener componentAdded(ContainerEvent evt), componentRemoved(ContainerEvent evt)
FocusListener focusGained(FocusEvent evt), focusLost(FocusEvent evt)
KeyListener keyPressed(KeyEvent evt), keyReleased(KeyEvent evt), keyTyped(KeyEvent evt)
MouseListener mouseClicked(MouseEvent evt), mouseEntered(MouseEvent evt), mouseExited(MouseEvent evt), mousePressed(MouseEvent evt), mouseReleased(MouseEvent evt)
MouseMotionListener mouseDragged(MouseEvent evt), mouseMoved(MouseEvent evt)
WindowListener windowActivated(WindowEvent evt), windowClosed(WindowEvent evt), windowClosing(WindowEvent evt), windowDeactivated(WindowEvent evt), windowDeiconified(WindowEvent evt), windowIconified(WindowEvent evt), windowOpened(WindowEvent evt)
Adapter classes 
 
Event adapters facilitate implementing listener interfaces. Many event listener interfaces have more than one event listener methods. For such interfaces, Java technology defines adapter classes. These have empty implementation (stubs) of all the event listener methods defined in the interface they implement. A listener can subclass the adapter and override only stub methods for handling events of interest. The table below lists the low level event listener interfaces and their adapters.

Table Event Listener Interfaces and their corresponding adapter classes. 
 
Event Listener interface Event Listener Adapter
ComponentListener ComponentAdapter
ContainerListener ContainerAdapter
FocusListener FocusAdapter
KeyListener KeyAdapter
MouseListener MouseAdapter
MouseMotionListener MouseMotionAdapter
WindowListener WindowAdapter


Java AWT: Delegation Event Model

In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The model for event processing in version 1.0 of the AWT is based on inheritance. In order for a program to catch and process GUI events, it must subclass GUI components and override either action() or handleEvent() methods. Returning "true" from one of these methods consumes the event so it is not processed further; otherwise the event is propagated sequentially up the GUI hierarchy until either it is consumed or the root of the hierarchy is reached. The result of this model is that programs have essentially two choices for structuring their event-handling code:
  1. Each individual component can be subclassed to specifically handle its target events. The result of this is a plethora of classes.
  2. All events for an entire hierarchy (or subset thereof) can be handled by a particular container; the result is that the container's overridden action() or handleEvent() method must contain a complex conditional statement in order to process the events.

Delegation Event Model

In the delegation event model,listener must register with a source in order to receiver an event notification .this provides an important benefits :notifications are sent  only to listeners that want to recieve the.This is a more efficient way to handle events than the design used by the java 1.0 approach ,Previously an event was propagated up the containment hierarchy until it was handled by a component .This required components to receive events that they did not process and is wasted valuable time .The delegation event model eliminates this overhead

The primary design goals of the new model in the AWT are the following:
  • Simple and easy to learn
  • Support a clean separation between application and GUI code
  • Facilitate the creation of robust event handling code which is less error-prone (strong compile-time checking)
  • Flexible enough to enable varied application models for event flow and propagation
  • For visual tool builders, enable run-time discovery of both events that a component generates as well as the events it may observe
  • Support backward binary compatibility with the old model
Note: These goals are described from the particular perspective of the AWT. Since this model has also been designed to accommodate the JavaBeans architecture, the design goals from the JavaBeans perspective are described in the "Events" section of the JavaBeans Specification and may vary slightly from these goals.

Delegation Model Overview

Event types are encapsulated in a class hierarchy rooted at java.util.EventObject. An event is propagated from a "Source" object to a "Listener" object by invoking a method on the listener and passing in the instance of the event subclass which defines the event type generated. A Listener is an object that implements a specific EventListener interface extended from the generic java.util.EventListener. An EventListener interface defines one or more methods which are to be invoked by the event source in response to each specific event type handled by the interface.
An Event Source is an object which originates or "fires" events. The source defines the set of events it emits by providing a set of set<EventType>Listener (for single-cast) and/or add<EventType>Listener (for mult-cast) methods which are used to register specific listeners for those events.
In an AWT program, the event source is typically a GUI component and the listener is commonly an "adapter" object which implements the appropriate listener (or set of listeners) in order for an application to control the flow/handling of events. The listener object could also be another AWT component which implements one or more listener interfaces for the purpose of hooking GUI objects up to each other.

Event Hierarchy

Events are no longer represented by a single Event class (like java.awt.Event) with numeric ids, but instead by a hierarchy of event classes. Each event class is defined by the data representing that event type or related group of events types. Since a single event class may be used to represent more than one event type (i.e. MouseEvent represents mouse up, mouse down, mouse drag, mouse move, etc), some event classes may also contain an "id" (unique within that class) which maps to its specific event types.
The event classes contain no public fields; the data in the event is completely encapsulated by proper get<Attr>()/set<Attr>() methods (where set<Attr>() only exists for attributes on an event that could be modified by a listener).

Event Delegation Model is based on four concepts:

The Event Classes
The Event Listeners
Explicit Event Enabling
Adapters

Passing Parameter to Applets with example

Java applet has the feature of retrieving the parameter values passed from the html page. So, you can pass the parameters from your html page to the applet embedded in your page. The param tag(<parma name="" value=""></param>) is used to pass the parameters to an applet. For the illustration about the concept of applet and passing parameter in applet


The applet has to call the getParameter() method supplied by the java.applet.Applet parent class. Calling getParameter("color") using the previous Java applet example would return a String value containing the text "blue". It is then left up to the applet to take advantage of this information and actually paint the text blue on the screen.
Here are three methods commonly used by applets:
• String getParameter(String name)-Returns the value for the specified parameter string
• URL getCodeBase()-Returns the URL of the applet
• URL getDocumentBase()-Returns the URL of the document containing the applet  



Program hai.java


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


  /*<APPLET code="hai" width="300" height="250">
<PARAM name="Message" value="Hai friend how are you ..?"></APPLET>*/
         
public class hai extends Applet {

  private String defaultMessage = "Hello!";

  public void paint(Graphics g) {
 
    String inputFromPage = this.getParameter("Message");
    if (inputFromPage == null) inputFromPage = defaultMessage;
    g.drawString(inputFromPage, 50, 55);
  
  }
 
}
Output 


Passing Parameter to Applets with example





You only need to change the HTML, not the Java source code. PARAMs let you customize applets without changing or recompiling the code.
This applet is very similar to the HelloWorldApplet. However rather than hardcoding the message to be printed it's read into the variable inputFromPage from a PARAM element in the HTML.
You pass getParameter() a string that names the parameter you want. This string should match the name of a PARAM element in the HTML page. getParameter() returns the value of the parameter. All values are passed as strings. If you want to get another type like an integer, then you'll need to pass it as a string and convert it to the type you really want.

The PARAM element is also straightforward. It occurs between <APPLET> and </APPLET>. It has two attributes of its own, NAME and VALUE. NAME identifies which PARAM this is. VALUE is the string value of the PARAM. Both should be enclosed in double quote marks if they contain white space.
An applet is not limited to one PARAM. You can pass as many named PARAMs to an applet as you like. An applet does not necessarily need to use all the PARAMs that are in the HTML. Additional PARAMs can be safely ignored.

Using the html APPLET tag


This section tells you most of what you need to know to use the <APPLET> tag. It starts by showing you the tag's simplest form. It then discusses some of the most common additions to that simple form: the <PARAM> tag, alternate HTML code and text, the CODEBASE attribute, and the ARCHIVE attribute. For a detailed description of the <APPLET> tag,

The applet tag is used to start an applet from both an HTML .Document and from an applet viewer .An applet viewer will execute each APPLET tag that's it finds in a separate window while web browsers like Netscape Navigator ,Internet Explorer ,and Hot-java will allow many applets on single page.

You should already have seen the simplest form of the <APPLET> tag:
<APPLET CODE=AppletSubclass.class WIDTH=anInt HEIGHT=anInt>
</APPLET>

Specifying Parameters

<APPLET CODE="Animator.class" WIDTH=460 HEIGHT=160>
<PARAM NAME="imageSource" VALUE="images/Beans">
<PARAM NAME="backgroundColor" VALUE="0xc0c0c0">
<PARAM NAME="endImage" VALUE=10>
<PARAM NAME="soundSource" VALUE="audio">
<PARAM NAME="soundtrack" VALUE="spacemusic.au">
<PARAM NAME="sounds"
    VALUE="1.au|2.au|3.au|4.au|5.au|6.au|7.au|8au|9.au|0.au">
<PARAM NAME="pause" VALUE=200>
. . .
</APPLET>
 

Required Attributes

Attribute Value Description
code URL Specifies the file name of a Java applet
object name Specifies a reference to a serialized representation of an applet

Optional Attributes

Attribute Value Description
align left
right
top
bottom
middle
baseline
Specifies the alignment of an applet according to surrounding elements
alt text Specifies an alternate text for an applet
archive URL Specifies the location of an archive file
codebase URL Specifies a relative base URL for applets specified in the code attribute
height pixels Specifies the height of an applet
hspace pixels Defines the horizontal spacing around an applet
name name Defines the name for an applet (to use in scripts)
vspace pixels Defines the vertical spacing around an applet
width pixels Specifies the width of an applet

Standard Attributes

The <applet> tag supports the following standard attributes in HTML 4.01:

Attribute Value Description
class classname Specifies a class name for an element
id id Specifies a unique id for an element
style style_definition Specifies an inline style for an element
title text Specifies extra information about an element

 

Set Status Message in Applet Window Example

In addition to displaying information in its window ,an applet can also output a message to the status window of the browser or applet viewer on which it is running to do so ,call showStatus() with the string that you want displayed.Th status window is a good place to give the user feedback about what is occurring in the applet,suggest options ,or possibly report some types of errors .The status window also make an excellent debugging aid because it gives you an easy way to output information about your applet

Sample program  SetStatusMessageExample.java

import java.applet.Applet;
import java.awt.Graphics;

 /*
<applet code="SetStatusMessageExample" width=200 height=200>
</applet>
*/

public class SetStatusMessageExample extends Applet
{

        public void paint(Graphics g)
         {
                /*
                 * Show status message in an Applet window using
                 * void showStatus(String msg) method of an applet class.
                 */
             
                //this will be displayed inside an applet
                g.drawString("Show Status Example", 50, 50);
             
                //this will be displayed in a status bar of an applet window
                showStatus("This is a status message of an applet window");
        }
}
Output 
Set Status Message in Applet Window Example



First java applet program

Before getting started, you'll need a compiler for Java, so that you can translate source code into something executable. You could, for example, download the Java Software Development Kit (abbreviated as JDK), which includes a compiler, utilities, example applets, and documentation. Be sure to get the JDK and not the JRE (Java Runtime Environment) -- the former allows you to compile Java programs, the latter only allows you to run them.
Many programmers also like to have an IDE (integrated development environment - a program that allows you to edit source code within a window and press a single button to compile and run your code) to help them work. If you download the JDK with Netbeans from Oracle's website, you'll have an IDE included with the development kit. Another popular IDE for Java is Eclipse (to work with Eclipse, it's probably best to first install the JDK, and next install Eclipse, so that Eclipse can detect the presence of the JDK during its installation process). Personally, I don't use any IDE, so I install the JDK without Netbeans or Eclipse, and run the Java compiler directly on a command line


Compile : Javac applet_name.java
Run       : appletviewer applet_name.java


Sample Program FirstApplet.java


import java.applet.*;
import java.awt.*;
/*<APPLET CODE="FirstApplet" WIDTH="800" HEIGHT="500">
</APPLET>*/
public class FirstApplet extends Applet
 {
   public void paint(Graphics g)
    {
      g.drawString("Welcome in Java Applet.",100,200);
   }
}
Output 

javac FirstApplet.java
appletviewer FirstApplet.java 


first running of applet program

Applet Skeleton And Lifecycle

Tuesday 13 November 2012
import java.awt.*;
import java.applet.*;

/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/

public class AppletSkel extends Applet
{
// Called first.

public void init()
{
// initialization
}

/* Called second, after init(). Also called whenever the applet is restarted. */

public void start()
{
// start or resume execution
}

// Called when the applet is stopped.
public void stop()
{
// suspends execution
}

/* Called when applet is terminated. This is the last method executed. */

public void destroy()
{
// perform shutdown activities
}

// Called when an applet's window must be restored.
public void paint(Graphics g)
{
// redisplay contents of window
}
}
When an applet begins, the AWT calls the following methods, in this sequence:

1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )

 

init( )

The init() method is called exactly once in an applet's life, when the applet is first loaded. It's normally used to read  parameter tags, start downloading any other images or media files you need, and set up the user interface. Most applets have init() methods.  

start( )

The start() method is called at least once in an applet's life, when the applet is started or restarted. In some cases it may be called more than once. Many applets you write will not have explicit start()methods and will merely inherit one from their super class. A start() method is often used to start any threads the applet will need while it runs.

Paint()

The paint() method is called each time your applet's output must br redrawn.This situation can occur for several reason .For example in which the applet is running may be overwritten by another window and the uncovered or the applet window may be minimized and the then restored. paint() is also called when the applet begins execution .Whatever the cause ,whenever the applet must redraw its output ,paint () is called .The paint() method has one parameter of type Graphics.This parameter will contain the graphics context which describes the graphics environment in which the applet is running.

stop( )

The stop() method is called at least once in an applet's life, when the browser leaves the page in which the applet is embedded. The applet's start() method will be called if at some later point the browser returns to the page containing the applet. In some cases the stop() method may be called multiple times in an applet's life. Many applets you write will not have explicit stop()methods and will merely inherit one from their superclass. Your applet should use the stop() method to pause any running threads. When your applet is stopped, it should not use any CPU cycles.


destroy( )

The destroy() method is called exactly once in an applet's life, just before the browser unloads the applet. This method is generally used to perform any final clean-up. For example, an applet that stores state on the server might send some data back to the server before it's terminated. many applets will not have explicit destroy() methods and just inherit one from their superclass.

Applet class in java programming


An applet is a small program that is intended not to be run on its own, but rather to be embedded inside another application. The Applet class must be the superclass of any applet that is to be embedded in a Web page or viewed by the Java Applet Viewer. The Applet class provides a standard interface between applets and their environment. The Applet class doesn't provide any genuine applicability on its own. Its purpose is to provide a super class from which custom applet classes are extended

Method
Description
destroy()
public void destroy()
Cleans up whatever resources are being held.
getAppletContext()
 public AppletContext getAppletContext()
Gets a handle to the applet context. Gets a handle to the applet context. The applet context lets an applet control the applet's environment which is usually the browser or the applet viewer.
getAppletInfo()
 public String getAppletInfo()
Return a string containing information about the author, version and copyright of the applet.
getAudioClip(URL)
public AudioClip getAudioClip(URL url)
Gets an audio clip.
getCodeBase()
 public URL getCodeBase()
Gets the base URL.
getDocumentBase()
 public URL getDocumentBase()
Gets the document URL.
getImage(URL)
public Image getImage(URL url, String name)
Gets an image given a URL.
getImage(URL, String)
  public Image getImage(URL url, String name)
Gets an image relative to a URL.
getParameter(String)
public String getParameter(String name)
Gets a parameter of the applet.
getParameterInfo()
 public String[][] getParameterInfo()
Returns an array of strings describing the parameters that are understoond by this applet.
init()
 public void init()
Initializes the applet.
isActive()
public boolean isActive()
Returns true if the applet is active.
play(URL)
 public void play(URL url,String name)
Play an audio clip.
play(URL, String)
 public void play(URL url)
Play an audio clip.
resize(int, int)
public void resize(int width,int height)
Request for the applet to be resized.
setStub(AppletStub)
 public final void setStub(AppletStub stub)
Set the applet stub.
stop()
public void stop()
Called to stop the applet.
showStatus(String)
 public void showStatus(String msg) 
Show a status message in the Applet's context.
start()
        
public void start()
Called to start the applet.


The Java class library provides the Applet class with default implementation for all the applet methods. You can implement these methods in the applet class when you want to override the default implementation of these methods. In your example, you are extending the applet1 class to Applet class, therefore the methods are already implemented.By defining the init(), start() and paint() method,you are overriding the applet methods. Therefore if you will haven't define the init() or start() methods, the paint() method can still be invoked.

Java Applet Basics, Applet Complete tutorial


All applets are subclasses of Applet .Thus,all applets must import java.applet .Applets mus also import java.awt.Recall that awt stands for the Abstract window too kit.Since all applets run in a window ,It is necessary to iclude support for that window .Applets are not executed by the consile based java run time interpreter.Rather they are executed by either a Web browser or applet viewer .An applet can be a fully functional Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application, including the following:

  • An applet is a Java class that extends the java.applet.Applet class.
  • A main() method is not invoked on an applet, and an applet class will not define main().
  • Applets are designed to be embedded within an HTML page.
  • When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's machine.
  • A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment.
  • The JVM on the user's machine creates an instance of the applet class and invokes various methods during the applet's lifetime.
  • Applets have strict security rules that are enforced by the Web browser. The security of an applet is often referred to as sandbox security, comparing the applet to a child playing in a sandbox with various rules that must be followed.
  • Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

Advantages

A Java applet can have any or all of the following advantages:
  • It is simple to make it work on Linux, Microsoft Windows and Mac OS X i.e. to make it cross platform. Applets are supported by most web browsers.
  • The same applet can work on "all" installed versions of Java at the same time, rather than just the latest plug-in version only. However, if an applet requires a later version of the Java Runtime Environment (JRE) the client will be forced to wait during the large download.
  • Most web browsers cache applets so will be quick to load when returning to a web page. Applets also improve with use: after a first applet is run, the JVM is already running and starts quickly (the JVM will need to restart each time the browser starts afresh). It should be noted that JRE versions 1.5 and greater stop the JVM and restart it when the browser navigates from one HTML page containing an applet to another containing an applet.
  • It can move the work from the server to the client, making a web solution more scalable with the number of users/clients.
  • If a standalone program (like Google Earth) talks to a web server, that server normally needs to support all prior versions for users which have not kept their client software updated. In contrast, a properly configured browser loads (and caches) the latest applet version, so there is no need to support legacy versions.
  • The applet naturally supports the changing user state, such as figure positions on the chessboard.
  • Developers can develop and debug an applet direct simply by creating a main routine (either in the applet's class or in a separate class) and calling init() and start() on the applet, thus allowing for development in their favorite Java SE development environment. All one has to do after that is re-test the applet in the AppletViewer program or a web browser to ensure it conforms to security restrictions.
  • An untrusted applet has no access to the local machine and can only access the server it came from. This makes such an applet much safer to run than a standalone executable that it could replace. However, a signed applet can have full access to the machine it is running on if the user agrees.
  • Java applets are fast - and can even have similar performance to native installed software.

Disadvantages

A Java applet may have any of the following disadvantages:
  • It requires the Java plug-in.
  • Some browsers, notably mobile browsers running Apple iOS or Android do not run Java applets at all.
  • Some organizations only allow software installed by the administrators. As a result, some users can only view applets that are important enough to justify contacting the administrator to request installation of the Java plug-in.
  • As with any client-side scripting, security restrictions may make it difficult or even impossible for an untrusted applet to achieve the desired goals. However, simply editing the java.policy file in the JAVA JRE installation, one can grant access to the local filesystem or system clipboard for example, or to other network sources other than the network source that served the applet to the browser.
  • Some applets require a specific JRE. This is discouraged.
  • If an applet requires a newer JRE than available on the system, or a specific JRE, the user running it the first time will need to wait for the large JRE download to complete.
  • Java automatic installation or update may fail if a proxy server is used to access the web. This makes applets with specific requirements impossible to run unless Java is manually updated. The Java automatic updater that is part of a Java installation also may be complex to configure if it must work through a proxy.
  • Unlike the older applet tag, the object tag needs workarounds to write a cross-browser HTML document.
  • There is no standard to make the content of applets available to screen readers. Therefore, applets can harm the accessibility of a web site to users with special needs.

/*<applet code="Myapplet" width=200 height=200></applet>*/

This comment contains a n applet tag that will run an applet called Myapplet in a window that is 200 pixel wide and 200 pixel hight .Since th inclusion of an applet of an APPLET command makes applets easier.

Java interface complete tutorial

An interface in the Java programming language is an abstract type that is used to specify an interface (in the generic sense of the term) that classes must implement. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final). An interface may never contain method definitions.

Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement all of the methods described in the interface, or be an abstract class. Object references in Java may be specified to be of an interface type; in which case, they must either be null, or be bound to an object that implements the interface.

One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java must have exactly one base class, the only exception being java.lang.Object (the root class of the Java type system); multiple inheritance of classes is not allowed.

interface are designed to supperot dynamic method resolution at run time .Normally  in order for a method to be called from one class to another ,both classes need to be present at compile time so the java compiler can check to ensure  that the method signatures are compitable .This requirement by itself makes for a static and nonextensible classing environement .Inevitably in a system like this functionality gets pushed up higher and higher in the class  hierarchy so that the mechanisam will be available to more and more subclasses .Interfaces are designed to avoid this problem .They disconnect the definition of a method or set of methods from the inheritance hierachy .Since interfaces are in a different hierarchy from classes .It is possible for classes that are unrelated in terms of  the class hierachy to implement the same interface .This is where the real power of the interfaces is realized


Defining an interface



[visibility] interface InterfaceName [extends other interfaces] 
{
        constant declarations
        abstract method declarations
}

The body of the interface contains abstract methods, but since all methods in an interface are, by definition, abstract, the abstract keyword is not required. Since the interface specifies a set of exposed behaviors, all methods are implicitly public.


Thus, a simple interface may be


public interface Area
  {
     
       void areacalc(int p);
  }


The member type declarations in an interface are implicitly static, final and public, but otherwise they can be any type of class or interface.


The syntax for implementing an interface uses this formula:


implements InterfaceName[, another interface, another, ...]



Classes may implement an interface. For example,



public class cal  implements Area 
{

        public void Area (int p)
         {
               // programming to eat prey p (specifically for a lion)
         }
}


If a class implements an interface and does not implement all its methods, it must be marked as abstract. If a class is abstract, one of its subclasses is expected to implement its unimplemented methods. Although if any of the abstract class' subclasses does not implement all interface methods, the subclass itself must be marked again as abstract.


Classes can implement multiple interfaces



public class calc  implements Area,...........



Interfaces are commonly used in the Java language for callbacks. Java does not allow the passing of methods (procedures) as arguments. Therefore, the practice is to define an interface and use it as the argument and use the method signature knowing that the signature will be later implemented.


Sample Program for finding area of a circle


Program: area.java

interface shape
 {
   
     public void area_cal(int r);
    
    
 }
class circle implements shape
 { 

    public void area_cal(int r)
    {
       double a=3.14*r*r;
       System.out.println("The circle area is "+a);

    }
    
    
 }
public class area
{
         
    public static void main(String[] args)
    {
       
          shape circleshape=new circle();
         
             circleshape.area_cal(10);
    }
}
Output 



C:\java>javac area.java
C:\java>java area
The circle area is 314.0


Java interface complete tutorial


 

learn java programming Copyright © 2011-2012 | Powered by appsackel.org