Showing posts with label AWT Event Handling. Show all posts
Showing posts with label AWT Event Handling. Show all posts

Tuesday, 5 November 2013

Event Handling in Java for Beginners

Event Handling in Java for Beginners
Here is a quick tutorial on Event handling in Java for beginners. This tutorial contains every event listener interface and class you need to know.

Introduction

Any action that user performs on a GUI component must be listened and necessary action should to be taken. For example, if a user clicks on a Exit button, then we need to write code to exit the program. So for this, we need to know that the user has clicked the button. This process of knowing is called as listening and the action done by the user is called an event. Writing the corresponding code for a user action is called as Event handling.

An event listener in Java is an interface that contains methods called handlers in which corresponding action code is to be written.
An event class contains the information about an event.
Event source is the GUI component or model on which an event is generated or in other words an action is done.
An adapter class is an abstract class implementing a listener interface. This is essential when we don't want to write all the handlers. For example, MouseListener interface contains a lot of methods such as mousePressed(), mouseReleased().. and we want to write only one of them, we use adapter class. This class implements all the methods of an interface giving them an empty body while itself being abstract.

Dispatching of events

For every action user performs, a corresponding event object is generated. This generated event object should be sent to the corresponding listener so that we can handle that event and write the code accordingly. The process of sending of event object to its corresponding listener is called as event dispatching. Events cannot be dispatched if they aren't generated and an event, except MouseEvent cannot be generated on a disabled component.

Semantic vs Low level events

Low level events represent direct interaction with the user. They represent low level input such as keyboard or mouse. Here are a list of low level events.

java.awt.event.ComponentEvent

                    |

                    +-- java.awt.event.InputEvent

                    |                |

                    |                +-- java.awt.event.MouseEvent

                    |                +-- java.awt.event.KeyEvent

                    |

                    +-- java.awt.event.FocusEvent

                    |

                    +-- java.awt.event.ContainerEvent

                    |

                    +-- java.awt.event.WindowEvent
Semantic events are dependent events i.e. they depend on low level events. Sources of semantic events can be model like a Timer. Examples include ActionEvent, ItemEvent etc.

Event classes and their hierarchy

A GUI component can be registered to multiple listeners either of the same type or of different types supported by it.
Not all GUI components can generate all types of events. For example, a Frame cannot generate an ActionEvent

Event classes are the heart of event handling. They contain the information about the generated event. We need to learn them before we step into the concept. The AWT defines event classes that are also used in most of the Swing components.

java.util.EventObject  

        |

        +-- java.awt.event.AWTEvent

                    |

                    +-- ActionEvent

                    +-- AdjustmentEvent

                    +-- AncestorEvent

                    +-- ComponentEvent

                    +-- HierarchyEvent

                    +-- InputMethodEvent

                    +-- javax.swing.event.InternalFrameEvent

                    +-- InvocationEvent

                    +-- ItemEvent

                    +-- TextEvent

The super class of all the events is java.util.EventObject. This class contains getSource() method which returns the source of the generated event. An immediate sub class of EventObject is the AWTEvent class which is the super class of all AWT based events.

Examples on each event

ActionEvent

ActionEvent is generated on various AWT components like Button, TextField etc.
  1. Create ActionListener for AWT Button
  2. Create ActionListener for AWT MenuItem
  3. Using ActionListener for AWT TextField 
  4. Using ActionListener for AWT List 
  5. Using Shortcut for AWT MenuItem

ItemEvent

This event is generated whenever an item is selected/de-selected on a List or a Choice typically.
  1. Using ItemListener for AWT Checkbox
  2. Using ItemListener for AWT RadioButton
  3. Using ItemListener for AWT Choice
  4. Using ItemListener for AWT List

KeyEvent

This event is generated whenever user presses/releases or types a key.
  1. Using KeyListener for AWT TextField
  2. A Funny KeyEvent Prank in Java

TextEvent

This event is generated whenever there is a change in text of a text component such as TextField or TextArea.
  1. Using TextListener for AWT TextField

MouseEvent

This is generated whenever user performs an action with the mouse. These include pressing,releasing,clicking,entering,exiting,moving and dragging of mouse.
  1. Using MouseListener for AWT Frame 
  2. Using MouseMotionListener on AWT Frame

MouseWheelEvent

This is generated whenever user does something with his mouse wheel.
  1. Using MouseWheelListener on AWT Frame

WindowEvent

This is generated whenever there is a change in the window state such as minimized,maximized,activate,de-activated,opened,closing,closed.
  1. Using WindowListener for AWT Frame
  2. Close AWT Frame in Java using WindowListener

FocusEvent

This event is generated when a component gets the focus i.e. it is selected currently.
  1. Using FocusListener on AWT TextField
  2. Using FocusListener on AWT Button

ContainerEvent

This event is generated whenever a component is added or removed to a container.
  1. Using ContainerListener on AWT Frame

ComponentEvent

This event is generated whenever there is a change in the size,location,visibility of a component.
  1. Using ComponentListener for AWT Button

WindowFocusEvent

This event is generated whenever a window gets or loses focus.
  1. Using WindowFocusListener on AWT Frame

AdjustmentEvent

This event is generated whenever there is a value change in a scrollbar.
  1. Using AdjustmentListener for AWT Scrollbar
The above events will give you a core understanding of the AWT Event Handling which pushes you forward to get into the Swing's.
If you have time, refer to the official event handling tutorial in Swing as well.

Using AdjustmentListener for AWT Scrollbar

The following example illustrates use of AdjustmentEvent with AWT Scrollbar.

import java.awt.*;
import java.awt.event.*;
class ScrollbarEvent extends Frame implements AdjustmentListener
{
Scrollbar s;

    public ScrollbarEvent()
    {
        createAndShowGUI();
    }
  
    private void createAndShowGUI()
    {
        setTitle("Scrollbar with AdjustmentListener Demo");
        setLayout(new FlowLayout());
      
        // Create and add scrollbar
        s=new Scrollbar();
        add(s);
      
        // Make it fat!
        s.setPreferredSize(new Dimension(50,250));
      
        // Add adjustment listener
        s.addAdjustmentListener(this);
      
        setSize(400,400);
        setVisible(true);
    }
  
    // Called whenever the scrollbar value changes
    public void adjustmentValueChanged(AdjustmentEvent ae)
    {
        // Update the title
        setTitle("Current value: "+ae.getValue());
    }
  
    public static void main(String args[])
    {
        new ScrollbarEvent();
    }
}

ScrollbarEvent(): Code illustrating AdjustmentListener with AWT Scrollbar is written here.
new ScrollbarEvent(): Create object for the class ScrollbarEvent

Using AdjustmentListener for AWT Scrollbar

Previous: Using WindowFocusListener for AWT Frame

Using WindowFocusListener for AWT Frame

The following example illustrates use of WindowFocusEvent with AWT Frame.

import java.awt.*;
import java.awt.event.*;
class FrameFocusEvent extends Frame implements WindowFocusListener
{
    public FrameFocusEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Frame with FocusListener demo");
        setLayout(new FlowLayout());
       
        // Add window focus listener
        addWindowFocusListener(this);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public void windowGainedFocus(WindowEvent we)
    {
        setBackground(Color.WHITE);
    }
   
    public void windowLostFocus(WindowEvent we)
    {
        setBackground(Color.LIGHT_GRAY);
    }
   
    public static void main(String args[])
    {
        new FrameFocusEvent();
    }
}

FrameFocusEvent(): Code illustrating WindowFocusListener with AWT Frame is written here.
new FrameFocusEvent(): Create object for the class FrameFocusEvent

Using WindowFocusListener for AWT Frame

Next: Using AdjustmentListener for AWT Scrollbar
Previous: Using ComponentListener for AWT Button

Using ComponentListener for AWT Button

The following example illustrates use of ComponentEvent with AWT Button

import java.awt.*;
import java.awt.event.*;
class ButtonComponentEvent extends Frame implements ComponentListener
{
Button main;
Button resize,show,move;

    public ButtonComponentEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("ComponentEvent on Button");
        setLayout(new FlowLayout());
       
        // Create buttons
        main=new Button("Main Button");
        resize=new Button("Increase size");
        show=new Button("Show/Hide");
        move=new Button("Move down");
       
        // Add ActionListener to buttons
        resize.addActionListener(new ResizeListener());
        show.addActionListener(new ShowListener());
        move.addActionListener(new MoveListener());
       
        // Add ComponentListener to main button
        main.addComponentListener(this);
       
        // Add all buttons
        add(main);
        add(resize);
        add(show);
        add(move);
   
        setSize(400,400);
        setVisible(true);
    }
   
    // For any ComponentEvent, just update the title
    public void componentResized(ComponentEvent ce)
    {
        setTitle("Resized to ["+main.getWidth()+","+main.getHeight()+"]");
    }
   
    public void componentMoved(ComponentEvent ce)
    {
        setTitle("Moved to ["+main.getX()+","+main.getY()+"]");
    }
   
    public void componentShown(ComponentEvent ce)
    {
        setTitle("Button is visible");
    }
   
    public void componentHidden(ComponentEvent ce)
    {
        setTitle("Button is hidden");
    }
   
    public static void main(String args[])
    {
        new ButtonComponentEvent();
    }

    // The listener implementations
   
    class ResizeListener implements ActionListener
    {
        public void actionPerformed(ActionEvent ae)
        {
            // Increase width,height by 1
            main.setSize(main.getWidth()+1,main.getHeight()+1);
        }
    }

    class ShowListener implements ActionListener
    {
        public void actionPerformed(ActionEvent ae)
        {
            // If visible, hide else show
            main.setVisible(!main.isVisible());
        }
    }

    class MoveListener implements ActionListener
    {
        public void actionPerformed(ActionEvent ae)
        {
            // Move down 5 units from current location
            main.setLocation(main.getX(),main.getY()+5);
        }
    }

}

ButtonComponentEvent(): Code illustrating ComponentListener with AWT Button is written here.
new ButtonComponentEvent(): Create object for the class ButtonComponentEvent

Using ContainerListener on AWT Frame

The following example illustrates using ContainerListener on AWT Frame.

import java.awt.*;
import java.awt.event.*;
class FrameContainerEvent extends Frame implements ContainerListener
{
Button add,remove;
int i;

    public FrameContainerEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("ContainerEvent on AWT Frame");
        setLayout(new FlowLayout());
       
        // Create and add a button
        add=new Button("Add Label");
        add(add);
       
        remove=new Button("Remove Label");
        add(remove);
       
        // Add ActionListener to buttons
        add.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                addLabel();
            }
        });
       
        remove.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                removeLabel();
            }
        });
       
        // Add ContainerListener
        addContainerListener(this);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public void addLabel()
    {
        // Add the label
        add(new Label("Label "+i++));
       
        // For updating the UI when the label is added
        javax.swing.SwingUtilities.updateComponentTreeUI(this);       
    }
   
    public void removeLabel()
    {
        // If there are no labels, do nothing
        if(i<1) return;
       
        // Remove the last label
        remove(getComponents()[getComponents().length-1]);
       
        // Decrement i value
        i--;
       
        // Update gui
        javax.swing.SwingUtilities.updateComponentTreeUI(this);
    }
   
    public void componentAdded(ContainerEvent ce)
    {
        Label l=(Label)ce.getChild();
        setTitle("Added "+l.getText());
    }
   
    public void componentRemoved(ContainerEvent ce)
    {
        Label l=(Label)ce.getChild();
        setTitle("Removed "+l.getText());
    }
   
    public static void main(String args[])
    {
        new FrameContainerEvent();
    }
}

ContainerEvent is generated whenever a component is added or removed on/from a container.
getChild(): This method returns the component that is affected (added/removed whatever that applies). This returns Component which is typecasted here to Label
FrameContainerEvent(): Code illustrating the use of ContainerListener on AWT Frame is written here.

Using ContainerListener for AWT Frame

Next: Using ComponentListener for AWT Button
Previous: Using FocusListener on AWT Button

Using FocusListener on AWT Button

The following example illustrates use of FocusListener on AWT Button.

import java.awt.*;
import java.awt.event.*;
class ButtonFocusEvent extends Frame implements FocusListener
{
Button b1,b2;

    public ButtonFocusEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("FocusListener for Button");
        setLayout(new FlowLayout());
       
        // Create 2 buttons
        b1=new Button("Button 1");
        b2=new Button("Button 2");
           
        // Add them
        add(b1);
        add(b2);
       
        // Add FocusListeners
        b1.addFocusListener(this);
        b2.addFocusListener(this);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public void focusGained(FocusEvent fe)
    {
        // Get what button got focus
        Button b=(Button)fe.getSource();
        b.setForeground(Color.RED);
    }
   
    public void focusLost(FocusEvent fe)
    {
        // Get what button lost focus
        Button b=(Button)fe.getSource();
        b.setForeground(Color.BLACK);
    }
   
    public static void main(String args[])
    {
        new ButtonFocusEvent();
    }
}

ButtonFocusEvent(): Code illustrating FocusListener on AWT Button is written here.
new ButtonFocusEvent(): Create object for ButtonFocusEvent

Using FocusListener on AWT Button

Next: Using ContainerListener on AWT Frame
Previous: Using FocusListener for AWT TextField

Using FocusListener on AWT TextField

The following example illustrates using FocusListener with AWT TextField.

import java.awt.*;
import java.awt.event.*;
class TextFieldFocusEvent extends Frame implements FocusListener
{
TextField t1,t2;

    public TextFieldFocusEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("FocusListener for TextField");
        setLayout(new FlowLayout());
       
        // Create 2 textfields
        t1=new TextField(20);
        t2=new TextField(20);
       
        // Add them
        add(t1);
        add(t2);
       
        // Add FocusListeners
        t1.addFocusListener(this);
        t2.addFocusListener(this);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public void focusGained(FocusEvent fe)
    {
        // Get what textfield got focus
        TextField t=(TextField)fe.getSource();
        t.setBackground(Color.LIGHT_GRAY);
    }
   
    public void focusLost(FocusEvent fe)
    {
        // Get what textfield lost focus
        TextField t=(TextField)fe.getSource();
        t.setBackground(Color.WHITE);
    }
   
    public static void main(String args[])
    {
        new TextFieldFocusEvent();
    }
}


focusGained() is called when a component gets focus i.e. when it is selected or active. You'll understand it in practical. focusLost() is called when a component loses its focus. Here focused field gets light gray background and non-focused gets white background.

TextFieldFocusEvent(): The code illustrating the FocusListener on AWT TextField is invoked here.

Using FocusListener on AWT TextField

Next: Using FocusListener on AWT Button
Previous: Using WindowListener for AWT Frame

Using MouseWheelListener on AWT Frame

The following illustrates using MouseWheelListener on AWT Frame. MouseWheelEvent is generated when a mouse wheel is moved.
import java.awt.*;
import java.awt.event.*;
class FrameMouseWheelListener extends Frame implements MouseWheelListener
{
Label l;

    public FrameMouseWheelListener()
    {
        createAndShowGUI();
    }
    
    private void createAndShowGUI()
    {
        setTitle("MouseWheelEvent for Frame Demo");
        setLayout(new FlowLayout());
        
        l=new Label("I go up and down");
        add(l);
        
        // Add MouseWheelListener to this frame
        addMouseWheelListener(this);
        
        setSize(400,400);
        setVisible(true);
    }

    public void mouseWheelMoved(MouseWheelEvent me)
    {
    // Get current co-ordinates
    int x=l.getX();
    int y=l.getY();
    
    // Get the amount to scroll
    int amt=me.getScrollAmount();
    
        // -1 = upward; 1 = downward
        if(me.getWheelRotation()==-1)
        l.setLocation(x,y-amt);
        else
        l.setLocation(x,y+amt);
    }
    
    public static void main(String args[])
    {
        new FrameMouseWheelListener();
    }
}

When the mouse wheel is pushed to the opposite side then the label is moved upwards so is y-amt where y is the current y co-ordinate. Here, x co-ordinate is kept constant. Note that MouseWheelListener is added to the Frame and not to the Label but the effect is on Label.

FrameMouseWheelListener(): This invokes code illustrating the MouseWheelEvent on AWT Frame.

Using MouseWheelListener on AWT Frame

Next: Using WindowListener for AWT Frame
 Previous: Using MouseMotionListener on AWT Frame

Using MouseMotionListener on AWT Frame

The following illustrates use of MouseMotionListener on AWT Frame. MouseMotionListener listens to mouse moved and dragged events which fall under MouseEvent.

import java.awt.*;
import java.awt.event.*;
class FrameMouseMotionListener extends Frame implements MouseMotionListener
{
    public FrameMouseMotionListener()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("MouseEvent for Frame Demo");
        setSize(400,400);
        setVisible(true);
      
        // Add MouseMotionListener to this frame
        addMouseMotionListener(this);
    }

    public void mouseMoved(MouseEvent me)
    {
        setTitle("Moved: ["+me.getX()+","+me.getY()+"]");
    }
   
    public void mouseDragged(MouseEvent me)
    {
        setTitle("Dragged: ["+me.getX()+","+me.getY()+"]");
    }
   
    public static void main(String args[])
    {
        new FrameMouseMotionListener();
    }
}

Mouse dragging is moving it in the pressing state typically used in drag and drop
me.getX(): This method gets the x co-ordinate of the pointer.
me.getY(): This method gets the y co-ordinate of the pointer.
FrameMouseMotionListener(): This contains the code illustrating MouseMotionListener with AWT Frame.
new FrameMouseMotionListener(): This statement creates object for the class.

Using MouseMotionListener on AWT Frame

Next: Using MouseWheelListener on AWT Frame
Previous: Using MouseListener for AWT Frame

Monday, 4 November 2013

Using MouseListener for AWT Frame

The following illustrates using MouseListener for AWT Frame. MouseListener listens to MouseEvent such as mousePressed, mouseReleased, mouseClicked, mouseEntered, mouseExited.

import java.awt.*;
import java.awt.event.*;
class FrameMouseEvent extends Frame implements MouseListener
{
    public FrameMouseEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("MouseEvent for Frame Demo");
        setSize(400,400);
        setVisible(true);
       
        // Add MouseListener to this frame
        addMouseListener(this);
    }
   
    public void mouseEntered(MouseEvent me)
    {
        setBackground(Color.GRAY);
    }
   
    public void mouseExited(MouseEvent me)
    {
        setBackground(Color.WHITE);
    }
   
    public void mousePressed(MouseEvent me)
    {
        setBackground(Color.DARK_GRAY);
    }
   
    public void mouseReleased(MouseEvent me)
    {
        setBackground(Color.LIGHT_GRAY);
    }
   
    public void mouseClicked(MouseEvent me)
    {
        setBackground(Color.BLACK);
    }
   
    public static void main(String args[])
    {
        new FrameMouseEvent();
    }
}

To see the effect of mouseReleased(), try pressing the mouse at a point and releasing it at another point.
mouseClicked() means pressing and releasing a mouse button at the same point. mouseEntered() and mouseExited() are executed when the cursor enters and exits the frame respectively.

FrameMouseEvent(): This contains code that illustrates use of MouseListener with AWT Frame.
new FrameMouseEvent(): Creates an object for the FrameMouseEvent class.

Using MouseListener for AWT Frame

Next: Using MouseMotionListener on AWT Frame
Previous: Using TextListener for AWT TextField

Using TextListener for AWT TextField

The following illustrates use of TextListener with AWT TextField. TextListener listens to TextEvent which is generated when the text in a text component (a TextField or TextArea) changes.

import java.awt.*;
import java.awt.event.*;
class TextFieldTextEvent extends Frame implements TextListener
{
TextField t;

    public TextFieldTextEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("TextListener for TextField");
        setLayout(new FlowLayout());
       
        // Create textfield that shows upto 20 chars
        t=new TextField(20);
       
        // This object is object of TextListener since
        // it implements TextListener
        t.addTextListener(this);
       
        add(t);
       
        setSize(400,400);
        setVisible(true);
    }
   
    // Called whenever the text in a text component (here t) changes
    public void textValueChanged(TextEvent te)
    {
        // Update the frame title
        setTitle(t.getText());
    }
   
    public static void main(String args[])
    {
        new TextFieldTextEvent();
    }
}

The TextEvent class doesn't contain methods to get the text because you have them in the TextField class. This event is fired only when there is a change in the text (either deletion,addition). This is much similar to DocumentEvent in swing but unlike in DocumentListener, TextListener doesn't have separate methods (handlers) for insertion and deletion.

TextFieldTextEvent(): This contains code illustrating the use of TextListener with AWT TextField.
new TextFieldTextEvent(): This creates object for the class.

Using TextListener for AWT TextField

Next: Using MouseListener for AWT Frame
Previous: Using KeyListener for AWT TextField

Using KeyListener for AWT TextField

The following illustrates using KeyListener for AWT TextField. A KeyListener listens to key events such as key pressed, released and typed.

import java.awt.*;
import java.awt.event.*;
class TextFieldKeyEvent extends Frame implements KeyListener
{
TextField t;

    public TextFieldKeyEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("KeyListener for TextField");
        setLayout(new FlowLayout());
       
        // Create textfield that shows upto 20 chars
        t=new TextField(20);
       
        // This object is object of KeyListener since
        // it implements KeyListener
        t.addKeyListener(this);
       
        add(t);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public void keyPressed(KeyEvent ke)
    {
        // Set title to both key character and its ascii code
        setTitle("You pressed "+ke.getKeyChar()+" ["+ke.getKeyCode()+"]");
    }
   
    public void keyReleased(KeyEvent ke)
    {
        setTitle("You released "+ke.getKeyChar()+" ["+ke.getKeyCode()+"]");
    }
   
    public void keyTyped(KeyEvent ke)
    {
        setTitle("You typed "+ke.getKeyChar()+" ["+ke.getKeyCode()+"]");
    }
   
    public static void main(String args[])
    {
        new TextFieldKeyEvent();
    }
}

When you start typing text, the keyTyped() is executed only when the key is a type-able i.e. the key is any character (number or letter or special char) but not other keys like Shift,Caps Lock, Ctrl and so on. However, any key can be pressed and released. keyTyped() doesn't need to involve a key press and a release. keyTyped() is executed even if you didn't release the key. A key is typed means that it is visible where you have typed.

getKeyCode(): This method gets the ascii code of the key.
getKeyChar(): This method returns the key character. For keys like Ctrl,Shift and so on, a ? is returned.

Using KeyListener for AWT TextField

Next: Using TextListener for AWT TextField
Previous: Using Shortcut for AWT MenuItem

Using Shortcut for AWT MenuItem

The following illustrates using shortcut for AWT MenuItem with which you can fire an ActionEvent on the MenuItem.

import java.awt.*;
import java.awt.event.*;
class MenuItemShortcut extends Frame implements ActionListener
{
MenuBar mb;
Menu m;
MenuItem exit;
MenuShortcut s;

    public MenuItemShortcut()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Shortcut for MenuItem");
      
        // Create MenuBar, Menu, MenuItem
        mb=new MenuBar();
        m=new Menu("Menu");
        exit=new MenuItem("Exit");
      
        // The shortcut is Ctrl+x
        // Ctrl is automatically added for MenuItem
        s=new MenuShortcut(KeyEvent.VK_X);
      
        // Set the shortuct to exit
        exit.setShortcut(s);
      
        // Add ActionListener
        exit.addActionListener(this);
      
        // Add exit to menu and menu to menubar
        m.add(exit);
        mb.add(m);
      
        // Set menu bar to frame
        setMenuBar(mb);
      
        setSize(400,400);
        setVisible(true);
    }
   
    public void actionPerformed(ActionEvent ae)
    {
        // Terminate the program
        System.exit(0);
    }
   
    public static void main(String args[])
    {
        new MenuItemShortcut();
    }
}

Whenever user presses Ctrl+x then ActionEvent is fired on exit MenuItem and program is terminated.

Using Shortcut for AWT MenuItem

Next: Using KeyListener for AWT TextField
Previous: Using ActionListener for AWT List

Using ActionListener for AWT List

The following illustrates use of ActionListener for AWT List.

import java.awt.*;
import java.awt.event.*;
class ListAction extends Frame implements ActionListener
{
List l;

    public ListAction()
    {
        createAndShowGUI();
    }
  
    private void createAndShowGUI()
    {
        setTitle("List Action");
        setLayout(new FlowLayout());
       
        // Create and add items to list
        l=new List();
       
        l.add("Google");
        l.add("Yahoo!");
        l.add("Bing");
        l.add("Baidu");
       
        // Add list to frame
        add(l);
       
        // Add ActionListener
        l.addActionListener(this);
       
        setSize(400,400);
        setVisible(true);
    }
  
    public void actionPerformed(ActionEvent ae)
    {
        // Change the title
        setTitle("You double clicked "+l.getSelectedItem());
    }
  
    public static void main(String args[])
    {
        new ListAction();
    }
}

ListAction(): Code illustrating use of ActionListener with AWT List is written here.
Note: ActionEvent is generated when you double click on a list item.
You might also want to see using ItemListener for AWT List

Using ActionListener for AWT List

Using ActionListener for AWT MenuItem

The following illustrates use of ActionListener with AWT MenuItem.

import java.awt.*;

import java.awt.event.*;

class MenuItemAction extends Frame implements ActionListener

{

MenuBar mb;

Menu m;

MenuItem exit;



    public MenuItemAction()

    {

        createAndShowGUI();

    }

   

    private void createAndShowGUI()

    {

        setTitle("ActionListener for MenuItem");

      

        // Create MenuBar, Menu, MenuItem

        mb=new MenuBar();

        m=new Menu("Menu");

        exit=new MenuItem("Exit");

      

        // Add ActionListener

        exit.addActionListener(this);

      

        // Add exit to menu and menu to menubar

        m.add(exit);

        mb.add(m);

      

        // Set menu bar to frame

        setMenuBar(mb);

      

        setSize(400,400);

        setVisible(true);

    }

   

    public void actionPerformed(ActionEvent ae)

    {

        System.exit(0);

    }

   

    public static void main(String args[])

    {

        new MenuItemAction();

    }

}

MenuItemAction(): Code for using ActionListener with MenuItem is written here.
Note: To fire the ActionEvent you need to click on the MenuItem or select it and hit enter. Alternatively, you can also set a menu shortcut.

Using ActionListener for AWT MenuItem

Using ItemListener for CheckboxMenuItem

The following illustrates use of ItemListener with AWT CheckboxMenuItem.

import java.awt.*;
import java.awt.event.*;
class CheckboxMenuItemEvent extends Frame
{
CheckboxMenuItem c;
MenuBar mb;
Menu m;

    public CheckboxMenuItemEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("CheckboxMenuItem with ItemListener demo");
       
        // Create menubar and menu
        mb=new MenuBar();
        m=new Menu("Menu");
       
        // Create simple CheckboxMenuItem
        c=new CheckboxMenuItem("Check me");
       
        // Add ItemListener
        c.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie)
            {
                // Change frame title
                setTitle("You "+(c.getState()?"checked":"unchecked")+".");
            }
        });
       
        // Add checkboxmenuitem,menu and MenuBar
        m.add(c);
        mb.add(m);
        setMenuBar(mb);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new CheckboxMenuItemEvent();
    }
}

CheckboxMenuItemEvent(): Code illustrating use of ItemListener with AWT CheckboxMenuItem is written here.
A CheckboxMenuItem is a menu item that can be checked as you see in Notepad > Format > Wordwrap.

Using ItemListener for AWT CheckboxMenuItem

Next: Using ItemListener for AWT RadioButton
Previous: Using ItemListener for AWT Checkbox

Using ActionListener for AWT TextField

The following illustrates use of ActionListener for AWT TextField.

import java.awt.*;
import java.awt.event.*;
class TextFieldAction extends Frame
{
TextField t;
    public TextFieldAction()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("TextField with ActionListener demo");
        setLayout(new FlowLayout());
       
        // Create simple TextField that shows 20 chars
        t=new TextField(20);
       
        // Add ActionListener
        t.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                // Change frame title
                setTitle(t.getText());
            }
        });
       
        // Add the textfield
        add(t);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new TextFieldAction();
    }
}
TextFieldAction(): Code illustrating ActionListener on AWT TextField is written here.
new TextFieldAction(): Code that initializes the GUI is written here.

Just type the text and hit enter to change the title because ActionEvent is generated.
Using ActionListener for AWT TextField

Using ItemListener for AWT RadioButton

The following illustrates use of ItemListener with AWT RadioButton.

import java.awt.*;
import java.awt.event.*;
class RadioButtonItemEvent extends Frame implements ItemListener
{
Checkbox r1,r2;
CheckboxGroup cg;

    public RadioButtonItemEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        // Set frame properties
        setTitle("Checkbox with ItemListener demo");
        setLayout(new FlowLayout());
       
        // Create simple Checkboxes
        r1=new Checkbox("Male");
        r2=new Checkbox("Female");
       
        // Add ItemListeners for r1,r2
        r1.addItemListener(this);
        r2.addItemListener(this);
       
        // Create CheckboxGroup
        cg=new CheckboxGroup();
   
        // Add r1,r2 to CheckboxGroup
        r1.setCheckboxGroup(cg);
        r2.setCheckboxGroup(cg);
       
        // Add radio buttons
        add(r1);
        add(r2);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public void itemStateChanged(ItemEvent ie)
    {
        setTitle(ie.getItem()+" is selected.");
    }
   
    public static void main(String args[])
    {
        new RadioButtonItemEvent();
    }
}
RadioButtonItemEvent(): Code that illustrates ItemListener for AWT RadioButton is written here.
new RadioButtonItemEvent(): This constructor call does all the stuff.

Using ItemListener for AWT RadioButton

Using ItemListener for AWT Checkbox

The following illustrates using ItemListener with AWT Checkbox.

import java.awt.*;
import java.awt.event.*;
class CheckboxItemEvent extends Frame
{
Checkbox c;
    public CheckboxItemEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Checkbox with ItemListener demo");
        setLayout(new FlowLayout());
       
        // Create simple Checkbox
        c=new Checkbox("Check me");
       
        // Add ItemListener
        c.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie)
            {
                // Change frame title
                setTitle("You "+(c.getState()?"checked":"unchecked")+".");
            }
        });
       
        add(c);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new CheckboxItemEvent();
    }
}
CheckboxItemEvent(): Code illustrating ItemListener with AWT Checkbox is written here.
new CheckboxItemEvent(): Create object for the class CheckboxItemEvent

Using ItemListener for AWT Checkbox