JavaSwing by manimoney707

VIEWS: 206 PAGES: 60

More Info
									Chapter 12: AWT and Swing Components

Java provides the AWT control components, which contains classes that enable you to create standard components, such as buttons, labels, and text fields in Java. A Java component enables you to accept input from an end user. You can position AWT components in containers using the different layout managers.

The AWT Control Components

Java provides the AWT control components, which contains classes that enable you to create standard components, such as buttons, labels, and text fields in Java.   A Java component enables you to accept input from an end user. You can position AWT components in containers using the different layout managers.

Using Various AWT Components
 An AWT control is a component that enables end users to interact with applications created in Java.   All AWT controls in Java are subclasses of the Component class. The Component class provides the add() method to add AWT components to containers, such as an applet or a window. 
TextField: User interface components that accept text input from an end user. A

text field enables you to type text in a single line. An instance of the TextField class is used to create a text field. 
TextArea: Used to accept text input from an end user, but it enables you to type

text in multiple lines. An instance of the TextArea class is used to create a text area.



Button: Used for handling events. Java provides the Button class to create AWT

button components. 
List: Is a scrollable list of text items that enables you to select either one item or

multiple items. You create a list using the List class in Java. 
Checkbox: Exist in dual state, checked and unchecked. You can change the

state of a check box by clicking the check box. You create a check box using the CheckBox class. 
Choice: Used to create combination boxes that are also known as drop-down

menus using the Choice class in Java. You create a drop-down menu using the Choice class that enables you to select a single item from the menu. 
Labels: Used for displaying a single line of text in a container. You create a label

using the Label class.

An AWT control is a component that enables end users to interact with applications created in Java. All AWT controls in Java are subclasses of the Component class. The Component class provides the add() method to add AWT components, such as an applet or a window, to containers. The various classes that you can use for creating

AWT controls
       TextField TextArea Button List CheckBox Choice Label

The TextField
Class

Text fields are user interface components that accept text input from an end user. A text field enables you to type text in a single line. An instance of the TextField class is used to create a text field. The following list describes the various constructors that you can use to create an instance of the TextField class:    

public TextField(): Creates a new text field public TextField(int cols): Creates a new text field with the required number of columns public TextField(String text): Creates a new text field initialized with the default text public TextField(String text, int cols): Creates a new text field initialized with the default text and the required number of columns

The following table lists some of the methods of the TextField class:   

public int getColumns(): Returns the number of columns of the text field public String getText(): Returns the text contained in the text field public void setText(String text): Sets the required text to the text field

The TextArea
Class

Text areas are also used to accept text input from an end user, but it enables you to type text in multiple lines. An instance of the TextArea class is used to create a text area. The following list describes the some of the constructors that you can use to create an instance of the TextArea class:   

public TextArea():Creates a new text area public TextArea(int rows, int cols): Creates a new text area with the specified number of rows and columns public TextArea(String text): Creates a new text area with the specified text



public TextArea(String text, int rows, int cols, int scrollbar): Creates a new text area with the specified text, number of rows and columns, and visibility of the scroll bar

The following table describes some of the methods of the TextArea class:
Method Description

public int getColumns() public String getText() public void setText(String text) public int getRows() public void insert(String text, in pos)

Returns the number of columns of the text area Returns the text contained in the text area Sets the required text to the text area Retrieves the total number of rows of the text area Inserts the required text at the specified position in the text area

public void append(String text)

Appends the required text to the current text in the text area

The Button
Class

Buttons are AWT controls that are used for handling events. Java provides the Button class to create AWT button components. The following list describes the various constructors that you can use to create an instance of the Button class:    

public Button():Creates a button without any label public Button(String label): Creates a button with the required label The following list describes some of the methods of the Button class: public String getLabel():Retrieves the value of the label of the button public void setLabel(String label):Modifies the existing label of the button to the value specified by the label argument

The List
Class

List control is a scrollable list of text items that enables you to select either one item or multiple items. You create a list using the List class in Java. The following list describes some of the constructors that you can use to create an instance of the List class:

 

public List(): Creates a new scrolling list of items. public List(int rows, boolean multipleselection): Creates a new scrolling list of items with the total number of required rows. The parameter, multipleselection, enables you to select more than one item from the List control.

The following table describes some of the methods of the List class:

Method

Description

public void add(String item) public void add(String item,int index) public boolean removeAll (Collection c) public int getItemCount() public boolean remove(Object o)

Adds the specified item at the end of a list Adds the specified item at the defined position in a list Removes all the items of a list that are contained in the specified collection Retrieves the number of items from a list Removes the first occurrence of the specified item that is passed as an argument

public Object remove (int position) public int getMinimumSize(int rows)

Removes the specified item from this scrolling list Retrieves the minimum dimensions for a list with the specified number of rows

public int getSelectedIndex() public int getSelectedItem() public String getItem(int index)

Retrieves the index of the selected item from a list Retrieves the selected item from a list Retrieves an item of the scrolling list at the specified index position of a list

public void replaceItem(String newstring, int index) public void setMultipleMode(boolean b)

Replaces an item at the specified index position of a list Sets the flag that allows multiple selections in a scrolling list

The CheckBox
Class

Check boxes are the components that exist in dual state, checked and unchecked. You can change the state of a check box by clicking the check box. You create a check box

using the CheckBox class. The following list describes some of the constructors that you can use to create an instance of the CheckBox class:    

public CheckBox():Creates a check box without any label. public CheckBox(String labelText):Creates a check box with the specified label. public CheckBox(String labelText, boolean state): Creates a check box with the specified label and state. public CheckBox(String labelText, CheckBoxGroup group, boolean state): Creates check box with the specified label, state, and group.

The following table describes some of the methods of the CheckBox class:
Method

Description

public String getLabel() public void setLabel(String label) public boolean getState() public void setState(boolean state) public CheckBoxGroup getCheckBoxGroup() public void getCheckBoxGroup( CheckBoxGroup g)

Returns the label of the check box Sets the specified label for a check box Retrieves the state of the check box Sets the specified state for a check box Retrieves the check box group for the check box

Sets the specified check box group for a check box

The Choice
Class

You can create combination boxes that are also known as drop-down menus using the Choice class in Java. You create a drop-down menu using the Choice class that enables you to select a single item from the menu.

The public Choice() constructor is used to create a new choice menu when you create an instance of the Choice class. The following table describes the some of the methods of the Choice class:

Method

Description

public int getItemCount() public String getItem(int index)

Returns the total number of items of the choice menu Returns the String at the specified index of the choice menu

public void insert(String item, int index) public void remove(String item)

Inserts an item into a choice menu at the specified position Removes the first occurrence of an item from a choice menu

public void remove(int position)

Removes an item at the specified position from a choice menu

public void removeAll() public String getSelectedItem()

Removes all the items from a choice menu Returns the current selected item of a choice menu in the form of a string

public int getSelectedIndex()

Returns the index of the currently selected item of a choice menu

public void select(int pos)

Selects the text specified at the position by the pos argument

The Label
Class

Labels are used for displaying a single line of text in a container. You create a label using the Label class. The following list describes the various constructors that you can use to create an instance of the Label class:   

public Label():Creates an empty label public Label(String labelText):Creates a label with the specified text public Label(String labelText, int align):Creates a label with the specified text and specified alignment, such as Label.LEFT, Label.CENTER, and Label.RIGHT

The following table describes some of the methods of the Label class:
Method

Description

public int getAlignment() public void setAlignment( int alignment) public String getText() public void setText( String labelText)

Retrieves the current alignment of a Label Sets the alignment of the Label to the value specified as argument Retrieves the string value of the label Modifies the text of the label to the value passed as the labelText argument

Swing components
Swing components also provide GUI environment to Java in addition to applets. Swing components are a collection of lightweight visual components that provide a replacement for the heavyweight AWT components. The major difference between the lightweight visual components and heavyweight visual components is that lightweight components have transparent pixels while the latter are opaque.

Swing components contain the Pluggable Look and Feel (PL&F) feature that allows applications to have the same behavior on various platforms. For example, when you use AWT package, the appearance of the interface might vary across platforms. However, the swing components provide a consistent look and feel to the interface across platforms.

Identifying the Swing Component Class Hierarchy
 Swing components are a collection of lightweight visual components that provide a replacement for the heavyweight AWT components.  Swing components contain the Pluggable Look and Feel (PL&F) feature that allows applications to have the same behavior on various platforms.  Identifying the Swing Component Class Hierarchy.  The JComponent class is the root of the Swing hierarchy, which is an

extension of the AWT container class.  The class hierarchy of the Swing components is categorized into:  Top-level Swing Containers: Acts as a container for placing the intermediate-level and atomic swing components, such as panels, frames, buttons, and check boxes.  Intermediate-level Swing Containers: Placed on the top-level containers and contains atomic components.  Atomic Components: Placed on the intermediate-level swing containers. Atomic components are used to accept input from a user.

The JComponent class is the root of the Swing hierarchy, which is an extension of the AWT container class. The class hierarchy of the Swing components is categorized into: 

Top-level Swing Containers: Acts as a container for placing the intermediate-level

and atomic swing components, such as panels, frames, buttons, and check boxes. The various top-level swing containers are:     JFrame JApplet JDialog

Intermediate-level Swing Containers: Placed on the top-level containers and

contains atomic components, such as buttons, check boxes, and labels. The various intermediate-level swing components are:      JPanel JtabbedPane JscrollPane JToolBar

Atomic Components: Placed on the intermediate-level swing containers. Atomic

components are used to accept input from a user. The various atomic components are:

     

JTextField JComboBox JCheckBox JButton JLabel JTable

The following table lists the difference between AWT and Swing Components:
AWT Components

Swing Components

Are heavyweight visual components.

Are lightweight visual components.

Do not support the pluggable look and Supports the pluggable look and feel feature. feel feature. Cannot insert images in buttons and Inserts images in buttons and labels. labels.

Using the Top-level Swing Containers



JApplet

  

The JApplet class is an extension of the AWT applet class. The Swing components that contain an applet need to extend the JApplet class. The JApplet() constructor enables you to create a swing applet instance when you create an instance of the JApplet class.



JFrame

  

The JFrame class is an extension of the AWT Frame class. You cannot add components directly to JFrame.

JDialog

 

The JDialog class is an extension of the AWT java.awt.Dialog class. The JDialog class is used to create modal and non-modal dialog boxes.

Using the Intermediate Level Swing Containers
 JPanel



JPanel class is an extension of the JComponent class that provides a replacement for the AWT Panel class.

 

You create a panel and add various components to it. The panel is further added to the content pane, which represents the display area of a window, a dialog, or a frame.

 

JPanel supports all layout managers of AWT. By default, JPanel applies the flow layout manager.

The top-level components are present at the top of the Swing hierarchy. The various toplevel Swing components are:

JApplet
The JApplet class is an extension of the AWT applet class. The Swing components that contain an applet need to extend the JApplet class. You can add menu bars and toolbars using the JApplet class. The JApplet class includes various panes, such as content pane, layered pane, glass pane, and root pane. The JApplet() constructor enables you to create a swing applet instance when you create an instance of the JApplet class.

JFrame
The JFrame class is an extension of the AWT Frame class. A frame is a top-level window that contains the title, border, minimize, and maximize buttons. You cannot add components directly to JFrame. You need to add components to the content pane of the JFrame class.

The following list describes some of the constructors that you can use to create an

instance of the JFrame class:   JFrame(): Creates a new frame that is initially invisible JFrame(String str): Creates a new frame that is initially invisible with the specified title

JDialog
The JDialog class is an extension of the AWT java.awt.Dialog class. The JDialog class is used to create modal and non-modal dialog boxes. A modal dialog box does not enable you to interact with other windows until the dialog box is closed.

A non-modal dialog box enables you to interact with other windows while the dialog box is open. The JDialog class does not enable you to add components directly to a dialog box. The components are added to the content pane, which is a child class of the dialog box. The following table describes some of the constructors that you can use to create an instance of the JDialog class:
Constructor JDialog()

Description Creates a non-modal dialog box without a title and the specified Frame owner

JDialog(Dialog owner)

Creates a non-modal dialog box with the specified Dialog owner but without a title

JDialog(Dialog owner, boolean modal) JDialog(Dialog owner, String title) JDialog(Dialog owner, String title, boolean modal) JDialog(Frame owner)

Creates a modal or non-modal dialog box with the specified Dialog owner but without a title Creates a non-modal dialog box with the specified title and the specified Dialog owner Creates a modal or non-modal dialog box with the specified title and the specified frame owner Creates a non-modal dialog box with the specified Frame as an owner but without a title

JDialog(Frame owner, boolean modal) JDialog(Frame owner, String title) JDialog(Frame owner, String title, boolean modal)

Creates a modal or non-modal dialog box with the specified Frame owner but without a title Creates a non-modal dialog box with the specified title and the specified Frame owner Creates a modal or non-modal dialog box with the specified title and the specified Frame owner

Using the Intermediate-level Swing Containers
 JTabbedPane  The JTabbedPane class is used to create a tabbed pane component that enables you to switch between groups of components by clicking a tab with a given label.   Tabs are added to the JTabbedPane object by using the addTab() method. The JTabbedPane class enables you to add multiple components but it displays only a single component at a time.  Using the Atomic Components       JButton JTextField JCheckBox JComboBox JLabel JRadioButton

The intermediate-level containers are placed on the top-level containers. The various intermediate-level Swing components are: JPanel

JPanel class is an extension of the JComponent class that provides a replacement for the AWT Panel class. A panel is used to hold other Swing components. You create a panel and add various components to it. The panel is further added to the content pane, which represents the display area of a window, a dialog, or a frame. JPanel supports all layout managers of AWT. By default, JPanel applies the flow layout manager.

The following list describes the constructor that you can use to create an instance of the JPanel class:

   

JPanel(): Creates a new JPanel with double buffer and flow layout as the default layout JPanel(boolean isDoubleBuffered): Creates a new JPanel with flow layout and the specified buffering strategy JPanel(LayoutManager layout): Creates a new buffered JPanel with the specified layout manager JPanel(LayoutManager layout, boolean isDoubleBuffered): Creates a new JPanel with the specified layout

The JTabbedPane Class

The JTabbedPane class is used to create a tabbed pane component that enables you to switch between groups of components by clicking a tab with a given label. Tabs are added to the JTabbedPane object by using the addTab() method.

A tab is represented by an index, which corresponds to its position. The first tab has an index equal to 0. The JTabbedPane class enables you to add multiple components but it displays only a single component at a time.

The following list describes the some of the constructors that you can use to create an instance of the JTabbedPane class:  

JTabbedPane():Creates an empty tabbed pane with the default tab placement as „TOP‟ JTabbedPane(int tabPlacement):Creates an empty tabbed pane with the specified tab placement, such as TOP, BOTTOM, LEFT, or RIGHT

You can use the following code to create the TabPanel class by using the JTabbedPane class:

import javax.swing.*; import java.awt.*; import java.awt.event.*;

public class TabPanel extends JFrame { Container container; JTabbedPane tpane; JPanel red = new JPanel(); JPanel green = new JPanel(); JPanel blue = new JPanel(); public TabPanel() { super("Tabbed Panel"); container = getContentPane(); JPanel jpanel = new JPanel(new GridLayout(1, 1)); tpane = new JTabbedPane(); tpane.addTab("RED", red); tpane.addTab("BLUE", blue); tpane.addTab("GREEN", green); //tpane.setSelectedIndex(0); jpanel.add(tpane); container.add(jpanel); setSize(350,400); setVisible(true); }

/* Creating an instance of JPanel. */ JPanel myPanel = new JPanel();

public static void main(String args[]) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { e.printStackTrace(); } TabPanel tabpanel = new TabPanel(); } }

In the preceding code, the TabPanel class creates red, green, and blue panels. The TabPanel class creates a tabbed pane on each panel using the JTabbedPane class. The following figure shows the output of the preceding code:

Creating TabbedPane

Using the Atomic Components

Atomic components are used to accept input from an end user. The various atomic Swing components are:

The JButton Class
The JButton class enables you to add a button to an applet or a panel. You can display text or create an icon associated with a button. The following list describes some of the constructors that you can use to create an instance of the JButton class:

   

JButton(): Creates a button without any text or icon JButton(String str): Creates a button with the specified text JButton(Icon icn): Creates a button with the specified icon associated with it JButton(String str, Icon icn): Creates a button with the specified text and icon

You can use the following code snippet to create a button using the JButton class:

public class JBtn extends JApplet { public void init() { Container contentPane = getContentPane(); JButton b; b = new JButton("Submit"); contentPane.add(b); } }

In the preceding code snippet, the class JBtn extends the JApplet class. The JBtn class creates an instance of JButton and adds it to the content pane by using the add() method of a container. You obtain the content pane of the JApplet class by using the getContentPane() method.

The JTextField Class
The JTextField class creates a text field that enables you to edit a single line of text. The following list describes some of the constructors that you can use to create an instance of the JTextField class:    

JTextField():Creates a text field JTextField(int columns): Creates a text field with the specified number of columns JTextField(String str): Creates a text field initialized with the specified text JTextField(String str, int columns): Creates a text field initialized with the specified text and columns

You can use the following code snippet to create a text field using the JTextField class:

public class JTxtFld extends JApplet { public void init() { Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); JTextField tf; tf = new JTextField("Type your text here"); contentPane.add(tf); } }

In the preceding code snippet, the JTxtFld class creates a text field using the JTextField class. The text field is added to the content pane of the Swing applet using the add() method.

The JCheckBox Class
The JCheckBox class is an extension of check boxes created using AWT. The JCheckBox class creates a check box that contains a text string and an icon. The following list describes some of the constructors that you can use to create an instance of the JCheckBox class:    

JCheckBox(String str): Creates an unselected check box with the specified text JCheckBox(Icon icn): Creates an unselected check box with the specified icon JCheckBox(String str, Icon icn): Creates an unselected check box with the specified text and icon JCheckBox(String str, boolean state): Creates a check box with the specified text and boolean state. The Boolen state specifies that the check box is initially selected, if the specified state is true

 

JCheckBox(Icon icn, boolean state): Creates a check box with the specified icon and boolean state JCheckBox(String str, Icon icn, boolean state): Creates a check box with the specified text, icon, and boolean state

You can use the following code snippet to create a check box by using the JCheckBox class:

import javax.swing.*; import java.awt.*; import java.awt.event.*;

// <applet code="JChkBx" width = 250 height = 300 > </applet>

public class JChkBx extends JApplet { public void init() { Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); JCheckBox cb1 = new JCheckBox("Red"); contentPane.add(cb1); JCheckBox cb2 = new JCheckBox("White"); contentPane.add(cb2); } }

In the preceding code snippet, the JChkBx class creates instances of cb1 and cb2 check boxes using the JCheckBox class. These check boxes are created with Red and White as the specified text. The check boxes are added to the content pane of the swing applet using the add() method.

The JComboBox Class
The JComboBox class is a combination of a text field and a drop-down list. You can type in a value or select it from a list using the JComboBox. The JComboBox() constructor enables you to create a check box when you create an instance of the JComboBox class. The following list describes some of the methods of the JComboBox class:

 

public void addItem(Object s): Adds an item into a combo box public void insertItemAt(Object obj, int index): Adds an item at the specified position in a combo box

The following list describes the various constructors that you can use to create an instance of the JComboBox class:    

JComboBox(): Creates a default combo box JComboBox(ComboBoxModel aModel): Creates a combo box that takes its items from an existing ComboBoxModel JComboBox(Object[] items): Creates a combo box that contains the elements in the specified array JComboBox(Vector items): Creates a combo box that contains the elements in the specified vector

The JLabel Class

The JLabel class is used to display text and an image. By default, a label that displays text is left aligned and a label that displays image is horizontally centered. You can also change the alignment of a label. The following list describes the various constructors that you can use to create an instance of the JLabel class:      

JLabel():Creates a label with an empty string and no image JLabel(Icon img): Creates a label with the specified image JLabel(Icon img, int horizontalAlignment):Creates a label with the specified image and horizontal alignment JLabel(String txt): Creates a label with the specified text JLabel(String txt, Icon img, int horizontalAlignment): Creates a label with the specified text, image, and horizontal alignment JLabel(String txt, int horizontalAlignment): Creates a label with the specified text and horizontal alignment

You can use the following code snippet to create a label and a combo box using the JLabel and JComboBox class:

public class JLbCmbBx extends JApplet { JLabel lb; public void init() { Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); JLabel lb = new JLabel("Colors"); JComboBox jcb = new JComboBox(); jcb.addItem("red"); jcb.addItem("Black"); contentPane.add(jcb); contentPane.add(lb); } }

In the preceding code snippet, the JLbCmbBx class creates an lb label with Colors as the specified text. The JLbCmbBx class creates a jcb combo box. The red and black items are added to the combo box. The label and combo box are added to the content pane of the Swing applet.

The JRadioButton Class
The JRadioButton class creates a set of radio buttons, which are grouped using the ButtonGroup that enables you to select any one of the radio buttons at a time. The following list describes some of the constructors that you can use to create an instance of the JRadioButton class:    

JRadioButton(String str): Creates an unselected radio button with the specified text JRadioButton(Icon icn): Creates an unselected radio button with the specified icon JRadioButton(String str, Icon icn): Creates a radio button with the specified text and icon, initially unselected JRadioButton(String str, boolean state): Creates a radio button with the specified text and state. The radio button is initially selected, if the state is true



JRadioButton(Icon icn, Boolean state): Creates a radio button with the specified icon and state. The radio button is initially selected, if the state is true

You can use the following code snippet to create a radio button using the JRadioButton class:

public class JRdoBtn extends JApplet { public void init() { Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); JRadioButton b1= new JRadioButton("M"); contentPane.add(b1); JRadioButton b2= new JRadioButton("F"); contentPane.add(b2); ButtonGroup bg = new ButtonGroup(); bg.add(b1); bg.add(b2); } }

In the preceding code snippet, the JRdoBtn class creates b1 and b2 radio buttons. These radio buttons are added to the content pane of the Swing applet and are associated with the bg ButtonGroup.

Using Layout Managers
The layout managers are used to position the components, such as an applet, a panel, or a frame in a container. The layout managers implement the java.awt.LayoutManager interface. A layout manager is an instance of the LayoutManager interface in Java.

You can use the following method to apply the desired layout to the components:

void setLayout(layoutManager obj)

In the preceding syntax, obj is the reference to the desired layout manager. Java has various predefined classes of layout managers. All layout managers make use of the setLayout() method to set the layout of a container. If the setLayout() method is not used, then the default layout of the container is set.

The different types of layout managers are:     

FlowLayout Manager BorderLayout Manager GridLayout Manager CardLayout Manager GridBagLayout Manager

Using the FlowLayout Manager

The Flowlayout is the default layout manager used for the Applet class. In the flow layout manager, the components are placed in a container window in a sequence one after the other in rows. The flow layout places the components as text is placed in MS Word document, where the word wrapping feature is enabled. The placement of the component depends on the dimensions, such as the width and height of the container window. In other words, the flow layout organizes the components in an order, left to right.

Java provides the FlowLayout class to apply flow layout to the various components that you are inserting in an applet.

The following list describes the various constructors that you can use to create an instance of the FlowLayout class: 

FlowLayout():Constructs a flow layout with the centered alignment and leaving a horizontal and vertical space of 5 pixels between the components



FlowLayout(int align): Constructs a flow layout with the specified alignment and

leaving a horizontal and vertical space of 5 pixels between the components. The valid values of align variable are LEFT, RIGHT, and CENTER  FlowLayout(int align, int hgap,int vgap): Constructs a flow layout with the specified alignment and leaving the specified horizontal and vertical space between the components

You can use the following code to apply flow layout to the components inserted in an applet:

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

// <Applet Code = FLayoutMan.class Width = 300 height = 200> </Applet>

public class FLayoutMan extends Applet { public void init() { setLayout(new FlowLayout(FlowLayout.CENTER)); Button a,b,c; a = new Button("Add"); b = new Button("Update"); c = new Button("Delete"); add(a); add(b); add(c); } }

In the preceding code snippet, the FLayoutMan class creates a, b, c buttons with the Add, Update, and Delete labels. The FLayoutMan class applies the flow layout to these buttons.

The following figure shows the output of the preceding code:

FlowLayout Manager

Using the BorderLayout Manager
BorderLayout is the default layout of the Frame class. The BorderLayout layout manager divides the container into north, south, east, west, and centre regions. You can place five components or controls in each part. Java provides the BorderLayout class to apply the border layout to the components.

The setLayout() method is used for applying border layout to a container. You specify the directions for the BorderLayout using the BorderLayout.NORTH, BorderLayoutSOUTH, BorderLayout.EAST, BorderLayout.WEST, and BorderLayout.CENTER Constants.

The following list describes the various constructors that you can use to create an instance of the BorderLayout class:  

BorderLayout():Creates a border layout with no space between the components BorderLayout(int h, int v): Creates a border layout specifying the horizontal and vertical space between the components

You can use the following code to apply BorderLayout to the components inserted in an applet:

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

// <Applet Code = BLayoutMan.class Width = 300 height = 200> </Applet>

public class BLayoutMan extends Applet { public void init() { setLayout(new BorderLayout()); Button a, b, c, d; a= new Button("Add"); b = new Button("Update"); c = new Button("Delete"); d = new Button("Reset"); add(a, BorderLayout.EAST); add(b,BorderLayout.NORTH); add(c,BorderLayout.SOUTH); add(d,BorderLayout.WEST); } }

In the preceding code, the BLayoutMan class creates a, b, c, and d buttons with labels Add, Update, Delete, and Reset. The BLayoutMan class applies the border layout to these buttons. The following figure shows the output of the preceding code:

Using

BorderLayout Manager

Using the GridLayout Manager
The grid layout is the layout that divides the container into rows and columns. The components are then added to the layout in cells. The intersection of a row and a column of the grid layout is called cell.

The GridLayout class of Java enables you to create a grid layout. All the components in a grid are of the same size. The position of a component in a grid is determined by the order in which the components are added to the grid. The following table describes the various constructors that you can use to create an instance of the GridLayout class:   

GridLayout(): Creates a grid layout with a default of one column per component in a single row GridLayout(int r, int c): Creates a grid layout with the specified number of rows and columns GridLayout(int r, int c, int h, int v): Creates a grid layout with the specified number of rows and columns and the specified horizontal and vertical space between the components

You can use the following code to apply the grid layout to the components inserted in an applet:

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

// <Applet code = GLayoutMan width = 300 height = 100> </Applet>

public class GLayoutMan extends Applet { public void init() { setLayout(new GridLayout(2,3)); add(new Button("Red")); add(new Button ("White")); add(new Button ("Green")); add(new Button ("Blue"));

add(new Button ("Black")); add(new Button ("Cyan")); } } In the preceding code, the GLayoutMan class creates Red, White, Green, Blue, Black, and Cyan buttons and applies the grid layout to these buttons.

The following figure shows the output of the preceding code:

GridLayout Manager

Using the CardLayout Manager
The CardLayout class is used to implement an area that contains different components at different times. The CardLayout is often controlled by a combo box, and the state of the combo box determines which panel (group of components) CardLayout displays.

The following are the various constructors that can be used to create an instance of the CardLayout class:  

CardLayout(): Creates a grid layout with a default of one column per component in a single row CardLayout(int hgap, int vgap): Creates a new card layout with the specified horizontal and vertical gaps

You can use the following code to apply the gridbaglayout to the components inserted in an applet:

import java.awt.*; import java.awt.event.*; import javax.swing.*;

public class CardLayoutDemo implements ItemListener { JPanel cards; //a panel that uses CardLayout final static String BUTTONPANEL = "James"; final static String TEXTPANEL = "Bill"; public void addComponentToPane(Container pane) { //Put the JComboBox in a JPanel to get a nicer look. JPanel comboBoxPane = new JPanel(); //use FlowLayout String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL }; JComboBox cb = new JComboBox(comboBoxItems); cb.setEditable(false); comboBoxPane.setPreferredSize(new Dimension(140,30)); cb.addItemListener(this); comboBoxPane.add(cb); //Create the "cards". JPanel cardPanelOne = new JPanel(); cardPanelOne.add(new JButton("Send"));

JPanel cardPanelSecond = new JPanel(); cardPanelSecond.add(new JTextField("TextField", 20)); //Create the panel that contains the "cards". cards = new JPanel(new CardLayout()); cards.add(cardPanelOne, BUTTONPANEL); cards.add(cardPanelSecond, TEXTPANEL); pane.add(comboBoxPane, BorderLayout.PAGE_START); pane.add(cards, BorderLayout.CENTER); } public void itemStateChanged(ItemEvent evt) { CardLayout cardLayOut = (CardLayout)(cards.getLayout()); cardLayOut.show(cards, (String)evt.getItem()); }

private static void createAndShowGUI() { //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); //Create and set up the window. JFrame frame = new JFrame("CardLayoutDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. CardLayoutDemo demo = new CardLayoutDemo(); demo.addComponentToPane(frame.getContentPane()); //Display the window. // frame.pack();

frame.setSize(300,300); frame.setVisible(true); } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { e.printStackTrace(); } javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }

Using the GridBagLayout Manager
GridBagLayout is a sophisticated and flexible layout manager. GridBagLayout places components in a grid of rows and columns, allowing specified components to span multiple rows or columns. Not all rows necessarily have the same height.

Similarly, not all columns necessarily have the same width. Essentially, GridBagLayout places components in rectangles (cells) in a grid and uses the components' preferred sizes to determine the size of the cells.

The following constructor can be used to create an instance of the GridBagLayout class:  

GridBagLayout() Creates a grid bag layout manager.

You can use the following code to apply gridbaglayout to the components inserted in an applet:

import javax.swing.*; import java.io.File; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.util.*;

public class UserCommunication extends JFrame implements ActionListener { private JMenuBar menubar; private JMenu filemenu; private JMenu propertmenu; private JTextArea sendertextarea; private JScrollPane senderscrollpane;

private JMenuItem openmenuitem,savemenuitem,exitmenuitem; private JMenuItem propertymenuitem,loadproperty,saveproperty;

JPanel buttonpanel; JButton openportbutton; JButton closeportbutton; JPanel textareapanel;

JComboBox comportcombo;

public UserCommunication() { super("User Commnucation"); createGUI(); }

public void createGUI() { Dimension scrnSize = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((scrnSize.width / 2) - 250, (scrnSize.height / 2) - 250); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName() }catch(Exception e) { System.out.println("Error in setting WLAF"+e); }

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentpane=getContentPane(); filemenu=new JMenu("File"); menubar=new JMenuBar(); filemenu.setMnemonic('f'); openmenuitem=new JMenuItem("Open"); openmenuitem.addActionListener(this); openmenuitem.setActionCommand("open"); openmenuitem.setMnemonic('o'); filemenu.add(openmenuitem); savemenuitem=new JMenuItem("Save"); savemenuitem.addActionListener(this); savemenuitem.setMnemonic('s'); savemenuitem.setActionCommand("save"); filemenu.add(savemenuitem); exitmenuitem=new JMenuItem("Exit"); exitmenuitem.addActionListener(this); exitmenuitem.setActionCommand("Exit");

exitmenuitem.setMnemonic('e'); filemenu.add(exitmenuitem); propertmenu=new JMenu("Properties"); propertymenuitem=new JMenuItem("Open Property Page"); propertymenuitem.addActionListener(this); propertymenuitem.setActionCommand("open_property"); propertymenuitem.setMnemonic('o'); loadproperty=new JMenuItem("Load From File"); loadproperty.addActionListener(this); loadproperty.setActionCommand("load_file"); loadproperty.setMnemonic('l'); saveproperty=new JMenuItem("Save Properties"); saveproperty.addActionListener(this); saveproperty.setActionCommand("save_property"); saveproperty.setMnemonic('s'); propertmenu.add(propertymenuitem); propertmenu.add(loadproperty); propertmenu.add(saveproperty); menubar.add(filemenu); menubar.add(propertmenu); setJMenuBar(menubar); buttonpanel=new JPanel(); openportbutton=new JButton("<html>O<u>p</u>en</html>"); openportbutton.setMnemonic('p'); openportbutton.setActionCommand("open_port"); closeportbutton=new JButton("<html><u>C</u>lose</html>"); closeportbutton.setMnemonic('C'); closeportbutton.setActionCommand("close_port"); GridBagLayout gridbaglayout=new GridBagLayout(); GridBagConstraints gridbagconstraint = new GridBagConstraints(); buttonpanel.setLayout(gridbaglayout); gridbagconstraint.fill = GridBagConstraints.HORIZONTAL; gridbagconstraint.insets=new Insets(5,5,5,5); gridbagconstraint.gridx=0;

gridbagconstraint.gridy=0; gridbagconstraint.anchor=GridBagConstraints.CENTER; gridbaglayout.setConstraints(openportbutton,gridbagconstraint); buttonpanel.add(openportbutton); gridbagconstraint.gridx=1; gridbagconstraint.gridy=0; gridbagconstraint.anchor=GridBagConstraints.CENTER; gridbaglayout.setConstraints(closeportbutton,gridbagconstraint); buttonpanel.add(closeportbutton); contentpane.add(buttonpanel,BorderLayout.SOUTH); textareapanel=new JPanel(new GridLayout(2,1,5,5)); sendertextarea=new JTextArea(); senderscrollpane=new JScrollPane(sendertextarea); textareapanel.add(senderscrollpane); contentpane.add(textareapanel,BorderLayout.CENTER); setSize(400,300); setVisible(true); }

public static void main(String args[]) { UserCommunication UserCommunication = new UserCommunication(); } public void actionPerformed(ActionEvent ae) { String componentid=ae.getActionCommand(); if (componentid=="open_port") { openportbutton.setEnabled(false); if(openPort()) { closeportbutton.setEnabled(false); } else { openportbutton.setEnabled(true); } }

if (componentid=="close_port") { closeportbutton.setEnabled(false); closePort(); } }

public boolean openPort() { return true; }

public boolean closePort() { return true; } }

Chapter 12: Event Handling

Event Handling in Java
An object that describes a change of state in a source component is called an event. The source components can be the elements of the Graphical User Interface (GUI). When you interact with these source components, their state changes; and this change of state causes various events to occur.

For example, pressing a mouse button, entering a character from the keyboard, selecting an item in a list, and moving a mouse generate events. The operating system traps the event and the data associated with it, such as the time at which the event occurred and the event type. The event type can be a mouse event, window event, or a mouse motion event. The operating system then passes this data to the application to which the event belongs.

Events can be generated even if there is no direct interaction of user with the GUI. For example, an event can be generated when a timer expires, some process, such as the printing of a document, is completed, or some hardware or software failure occurs. In Java, events are supported by the classes and interfaces defined in the java.awt.event package. The event-driven program contains objects with methods that control the various events and circumstances.

Identifying the Sources of Events
    An object that describes a change of state in a source component is called an event. The source components can be the elements of the Graphical User Interface (GUI). Events are supported by the classes and interfaces defined in the java.awt.event package. Identifying the Source of Events:

     

An event source is an object that generates an event. An event source registers some listeners, which receive notifications about a specific type of event generated by that particular event source. All the registered listeners are notified about the generation of an event and receive a copy of the event object. This is known as multicasting the event. Some sources allow only single listener to register. This is known as unicasting of event.

An event source is an object that generates an event. An event source registers some listeners, which receive notifications about a specific type of event generated by that particular event source. You can add setActionCommand with the event source and obtain the source of the generated event by using getActionCommand().

Sources of Events
Event sources are the Abstract Window Toolkit (AWT) GUI components, such as buttons, choice lists, and scroll bars. An event source can generate various types of events depending upon the change of state of the event source. For example, the List component creates an action event when an item is double-clicked and an item event when an item is selected or deselected.

The following table lists the various event sources and types of events they generate:
Event Source Description

Checkbox Button List

Creates an item event when a check box is selected or deselected. Creates an action event when a button is pressed. Creates an action event when an item is double-clicked; creates an item event when an item is selected or deselected.

Scrollbar Text Components

Creates an adjustment event when a scroll bar is scrolled. Creates a text event when a text character is entered in the text component

Window

Creates a window event when a window is activated, deactivated, opened, closed, or quit.

Event Listeners and Event Handlers
An event listener listens for a specific event and is notified when that specific event occurs. An event listener registers with one or more event sources to receive notifications about specific types of events and processes the events. An event-handler is called by the event listener whenever a specific event occurs.

In Java, event listeners are interfaces and the event-handler is a method declared in the event listener interface that is implemented by the application. The methods that are defined in the set of interfaces and classes found in the java.awt.event package receive and process the events.

For example, the MouseMotionListener interface defines two methods to receive notification when a mouse is moved or dragged.

An event source registers event listeners, which receive the notifications about a specific type of event generation. The syntax of a method that registers an event listener with an event source is:

public void addTYPEListener(TYPEListener obj)

In the preceding syntax, TYPE is a type of event that an event listener handles, such as an action event or an item event and obj is a reference to the event listener. For example, the addActionListener() method is used to register an action event listener and the addMouseMotionListener() method is used to register a mouse motion listener.

The Delegation Event Model
The delegation event model is based on the concept that source generates the event and notifies one or more event listeners. An event listener remains in a wait state until an event occurs. When an event is generated the event listeners are notified about the generation of event. After being notified by the sources the event listener processes the event.

The delegation event model allows you to specify the objects that are to be notified when a specific event occurs. If the event generated is not handled by the event listener then it is ignored by the event listener. In delegation event model, the event listener has to be registered with a source in order to get notified about the occurrence of a particular event. The registration process allows the event generation notification to be sent only to the registered listeners.

Event Class
The Java event class hierarchy

Java has a number of classes that describe different categories of events. The following figure shows the hierarchy of a Java event class:

The EventObject class, which is in the java.util package, is a superclass for all event classes. The public class EventObject from which all event objects are derived extends Object and implements the Serializable interface. The syntax of one of the constructors in the EventObject class is:

public EventObject(Object source)

In the preceding syntax, source is an object that generates an event. The EventObject class contains two methods, the getSource() method and the toString() method. The getSource() method returns the object on which event actually occurred. The toString() method returns the string representation of the object involved in an event.

The class AWTEvent is a subclass of the EventObject class but a superclass of all AWTbased events. The syntax of one of the constructors in the AWTEvent class is:

public AWTEvent(Object source,int id)

In the preceding syntax, source is an object where the event is originated and id is the type of event generated. The AWTEvent object is constructed with a specified event source and event type. The getID() method of AWTEvent class is used to get the type of event generated.

For example, if a mouse event occurs, you can use the getID() method to find out whether the event type is a click, drag, move, press, or a release from the event object. The subclasses of the java.awt.AWTEvent class represent the various event types that can be generated by the various AWT components. The various types of classes of AWT events are packaged in a separate package called the java.awt.event package.

The Action Event class
  ActionEvent is generated by an AWT component, such as a button, when a component-specific action is performed. The action event is generated when a button is pressed, a list item is doubleclicked, or a menu item is selected.



The following syntax shows the declaration of the constructor of the ActionEvent class is:

public ActionEvent(Object source, int id, String command) 

The main methods included in the Action Event class are:

String getActionCommand() int getModifiers()

ActionEvent is generated by an AWT component, such as a button, when a componentspecific action is performed. For example, the pressing of a button is an action being performed. The action event is generated when a button is pressed, a list item is doubleclicked, or a menu item is selected.

If an application performs some action, based on the generation of some action event then it implements the ActionListener interface. Each component, such as a button that generates an action event, registers the ActionListener to receive the events by calling its addActionListener() method.

The ActionEvent class has various types of constructors. The declaration of one of the constructors in the ActionEvent class is:

public ActionEvent(Object source, int id, String command)

In the preceding syntax, the ActionEvent object is constructed where source is the object that generates the action event, id is an integer that identifies the action event type. The command parameter is a String that specifies one of the commands associated with the events in the preceding syntax. The declaration of another type of constructor in the ActionEvent class is:

public ActionEvent(Object source, int id, String command,int modifiers)

In the preceding syntax, the argument modifiers indicate which of the modifier keys, such as ALT, CTRL, or SHIFT is pressed when an action event is generated.

The main methods included in the ActionEvent class are: 

String getActionCommand(): Finds out the command name for the related ActionEvent object. For example, pressing a button with mouse, generates an action event and you can get the label of that button by using the getActionCommand() method.



Int getModifiers(): Returns an integer value that indicates which of the modifiers keys, such as CTRL, ALT, and SHIFT are held down during the generation of an action event. ALT_MASK, CTRL_MASK, and SHIFT_MASK are the three integer constants defined in the ActionEvent class to identify the related modifiers associated with an action event.

The MouseEvent class
   The MouseEvent class extends the java.awt.event.InputEvent class. The mouse event indicates that a mouse action has occurred on a component. The mouse events include:       Pressing a mouse button Releasing a mouse button Clicking a mouse button Entering of mouse in a component area Exiting of mouse from a component area

The mouse event class defines some integer constants that can be used to identify several types of mouse events.

Various integer constants of the Event class:
Constants

Description

MOUSE_CLICKED MOUSE_DRAGGED MOUSE_MOVED MOUSE_PRESSED MOUSE_RELEASED MOUSE_ENTERED MOUSE_EXITED

Identifies the event of mouse clicking. Identifies the event of dragging of mouse Identifies the event of mouse moving. Identifies the event of mouse pressing. Identifies the event of mouse releasing Identifies the event of mouse entering an AWT component Identifies the event of mouse exiting an AWT component

The following syntax shows the declaration of one of the constructors of the MouseEvent class:

public MouseEvent(Component source, int eventType, long when, int modifiers, int x, int y, int clickCount, boolean triggersPopup )

Various methods of the MouseEvent class:
Methods

Description

public int getX()

Returns the horizontal x coordinate of the mouse position relative to a source component.

public int getY()

Returns the horizontal y coordinate of the mouse position relative to a source component.

public point getPoint()

Returns the Point object. The Point object contains the x and y coordinates of the mouse position relative to a source component.

public void translatePoint(int x, int y)

Translates the coordinates of a mouse event to a new position by adding x and y offsets.

public int getClickCount()

Returns the number of mouse clicks associated with an event.

Event Listener Interfaces
An event listener registers with an event source to receive notifications about the events of a particular type. An event listener is created by implementing one or more event listener interfaces defined by the java.awt.event package. An event listener interface defines one or more methods to handle events. Event listeners for handling different types of the events generated by the AWT components are defined in the java.awt.event package.

The following table lists the some of the event listener interfaces defined in the java.awt.event package:
Interface

Description

ActionListener

Defines the actionPerformed() method to receive and process action events.

MouseListener

Defines five methods to receive mouse events, such as when a Mouse is clicked, pressed, released, enters, or exits a component.

MouseMotionListener Defines two methods to receive events, such as when a mouse is dragged or moved. AdjustmentListener Defines the adjustmentValueChanged() method to receive and process the adjustment events. TextListener Defines the textValueChanged() method to receive and process an event when the text value changes. ItemListener Defines the itemStateChanged() method when an item has been selected or deselected by the user. WindowListener Defines seven window methods to receive events. These methods are: windowActivated(), windowClosed(), windowClosing(), windowDeactivated(), windowDeiconified(), windowIconified(), and windowOpened().

Using the ActionListener Interface
The class that processes action events implements the ActionListener interface. The syntax of the definition of the ActionListener interface is:

public interface ActionListener extends EventListener

The ActionListener interface has one method, actionPerformed(), which gets invoked when an action event occurs. The syntax of the actionPerformed() method is:

public void actionPerformed(ActionEvent ae)

The object of the class that implements the ActionListener interface is registered with a component using the addActionListener() method. The following code shows the generation of an action event and its handling by the ActionListener interface:

import javax.swing.*; import java.awt.*; import java.awt.event.*;

public class ActionTester extends JFrame implements ActionListener { JButton b1, b2; JLabel lbl; int clicked; final String str = " Number of times button clicked = ";

public ActionTester(String strName) { super(strName); getContentPane().setLayout(new FlowLayout()); JPanel p = new JPanel(); b1 = new JButton("Click Me"); b2 = new JButton("Quit"); p.setLayout( new FlowLayout() ); p.add(b1);

p.add(b2); lbl = new JLabel(str + clicked, JLabel.CENTER); getContentPane().add(p); getContentPane().add(lbl); b1.addActionListener(this); b2.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String s = ae.getActionCommand(); if("Click Me".equals(s)) { clicked++; lbl.setText(str + clicked); } if("Quit".equals(s) ) { System.exit(0); } }

public static void main(String args[]) { ActionTester t = new ActionTester("Action Events"); t.setSize(300,300); t.setVisible(true); } }

In the preceding code, the ActionTester class is created that extends JFrame and implements the ActionListener interface. An object of the ActionTester class is created in the main() method and constructor of the ActionTester class is called.

The super() method calls the constructor of the base class, JFrame and sets the title of the JFrame window.

The two objects, b1 and b2 of the JButton class are created with the Click Me and Quit labels respectively. The b1 and b2 components are placed in an object of JPanel that is

set with the FlowLayout layout. The lbl object of the JLabel class is placed in the JFrame window that displays the number of times the Click Me button is clicked. The action listeners are registered with the b1 and b2 components by calling the

addActionListener() method on them. When you click on any JButton component, an action event occurs and the actionPerformed() method is called. The

getActionCommand() method of the ActionEvent class is called in the actionPerformed() method to get the command string associated with the action event. If the command string is Click Me then the value of variable count is incremented by 1 otherwise the code exits. The setVisible() method makes the JFrame window visible.

The output of the preceding code is:

Using the ActionListener Interface
Example: Create an applet that contains a button. When you click the button, the label of

the button is changed from "Click here" to "Button clicked".

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

// <applet code="ButtonDemo.class" width=250 height=150> </applet>

public class ButtonDemo extends Applet implements ActionListener { Button b;

public void init() { b= new Button("Click here"); add("Center", b); b.addActionListener(this); }

public void actionPerformed(ActionEvent ae) { Button source = (Button)ae.getSource(); source.setLabel("Button clicked"); } }

The output of the preceding code is:

Before Button Click

After Button Click

The MouseListener interface is implemented for receiving various mouse events, such as when you press, click, release, enter, and exit a component. A class that processes the mouse events implements the MouseListener interface. The object of such class is registered as a listener for mouse events with a component using the

addMouseListener() method.

The following table lists the various public methods declared in the MouseListener interface:
Methods

Description

void mouseClicked(MouseEvent me)

Performs an action when the mouse button clicks a component.

void mousePressed(MouseEvent me)

Performs an action when the mouse button presses a component.

void mouseReleased(MouseEvent me)

Performs an action when the mouse button releases a component.

void mouseEntered(MouseEvent me)

Performs an action when the mouse button enters a component.

void mouseExited(MouseEvent me)

Performs an action when the mouse button exits a component.

The following code handles the various mouse events by implementing the MouseListener interface and prints the coordinates of the mouse position when the mouse event occurs:

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class mouseEventClass extends JFrame implements MouseListener, ActionListener { String str = " "; int mX = 0 , mY = 0; JLabel l; JButton b;

public mouseEventClass(String strName) { super(strName); GetContentPane().setLayout(new FlowLayout()); JPanel p =new JPanel(); p.setLayout(new FlowLayout()); l = new JLabel(str + mX + mY); getContentPane().add(l); b = new JButton("Quit"); p.add(b); getContentPane().add(p); addMouseListener(this); b.addActionListener(this); }

public void mouseClicked(MouseEvent me) { mX = me.getX(); mY = me.getY(); STR = "Mouse clicked at:"; l.setText(str+ mY + “,” + mX); }

public void mousePressed(MouseEvent me) { mX = me.getX(); mY = me.getY(); str = "Mouse pressed at : "; l.setText(str + mX + "," + mY); }

public void mouseReleased(MouseEvent me) { mX = me.getX(); mY = me.getY(); str = "Mouse Released at : "; l.setText(str + mX + "," + mY); }

public void mouseEntered(MouseEvent me) { mX = me.getX(); mY = me.getY(); str = "Mouse entered at: "; l.setText(str + mX + "," + mY); }

public void mouseExited(MouseEvent me) { mX = me.getX(); mY = me.getY(); str = "Mouse Exited at : "; l.setText(sty + mX + "," + mY); }

public void actionPerformed(ActionEvent ae) { String s= ae.getActionCommand(); if ( "Quit".equals(s)) { System.exit(0); } }

public static void main(String args[]) mouseEventClass ME = new

{

mouseEventClass("MouseEvents"); ME.setSize(300,300); ME.setVisible(true); } }

In the preceding code, the mouseEventClass is created that extends the JFrame class and implements the MouseListener and ActionListener interfaces. The object of mouseEventClass acts as a listener for the mouse events by calling the addMouseListener(this) method in the constructor.

When a mouse is pressed, clicked, released, entered, or exited from the JFrame window, a mouse event occurs and the corresponding method of the MouseListener interface is called. Each method of the MouseListener interface calls the getX() and getY() methods of the MouseEvent class to get the X, Y coordinates of mouse during the mouse event.

The output of the preceding code is:

Using Mouse Listener Interface

Using the MouseMotionListener
Interface

A mouse motion event is generated when the mouse is moved or dragged. A class that processes any mouse motion event implements the MouseMotionListener interface. The object of such class is registered as a listener for mouse motion events with a component using the addMouseListener() method. The syntax of the definition of the MouseMotionListener interface is:

public interface MouseMotionListener extends EventListener

The MouseMotionListener interface contains two methods for mouse move and mouse drag events. The syntax of the mouseDragged() method included in MouseMotionListener interface is:

public void mouseDragged(MouseEvent me)

The mouseDragged() method is invoked when mouse button is pressed on a component and then dragged. The syntax of the mouseMoved() method included in the MouseMotionListener interface is:

public void mouseMoved(MouseEvent me)

The mouseMoved() method is invoked when mouse is moved on the component but no button of mouse is pressed. The following code shows the generation of mouse motion event and its handling by the MouseMotionListener interface:

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class mouseMotion extends JFrame implements MouseMotionListener, ActionListener { String str = " "; int mX = 0, mY = 0; JLabel l; JButton b; public mouseMotion(String strName) { super(strName); getContentPane().setLayout(new FlowLayout()); Panel p =new Panel(); p.setLayout(new FlowLayout()); l = new JLabel(str + mX + mY); getContentPane().add(l); b = new JButton("Quit"); p.add(b); getContentPane().add(p); addMouseMotionListener(this); b.addActionListener(this); }

public void mouseMoved(MouseEvent me) { mX = me.getX(); mY = me.getY(); str = "Mouse Moving at:"; l.setText(str + mY + " " + mX); }

public void mouseDragged(MouseEvent me) { mX = me.getX(); mY = me.getY(); str = "Mouse Dragged at : "; l.setText(str + mX + " " + mY); }

public void actionPerformed(ActionEvent ae) { String s= ae.getActionCommand(); if ( "Quit".equals(s)) System.exit(0); }

public static void main(String args[]) { mouseMotion ME = new mouseMotion("MouseMotionEvents"); ME.setSize(300,300); ME.setVisible(true); } }

In the preceding code, the mouseMotion class is created that extends the JFrame class and implements the MouseMotionListener and ActionListener interfaces. The object of the mouseMotion class acts as a listener for the mouse motion events by calling the addMouseMotionListener(this) method in the constructor.

When a mouse is moved or dragged in the JFrame window, a mouse event occurs and the corresponding method of the MouseMotionListener interface is called. Each method of the MouseListener interface calls the getX() and getY() methods of the MouseEvent

class to get the X, Y coordinates of mouse during the mouse motion event.

The output of the preceding code is

Using Mouse Motion Listener Interface

Adapter Classes
The Java programming language provides adapter classes, which implement the event listener interfaces containing more than one event-handling method. An adapter class provides an empty implementation of the event-handling methods in an event listener interface.

When a class implements an event listener interface then it implements all the methods of that event listener. The methods are used to receive and process all the events that an event listener handles.

The adapter classes are useful as they allow you to receive and process only some of the events that are handled by a particular event listener interface. You can define a class that acts as an event listener by extending one of the adapter classes and overriding its methods to handle a particular type of event.

For example, the MouseMotionAdapter class has empty implementation of two methods, mouseDragged() and mouseMoved(). The signatures of these methods are same as defined in the MouseMotionListener interface. If you want to process only the mouse

drag events then you can extend a class by the MouseMotionAdapter class and implement the mouseDragged() method. The empty implementation of the

mouseMoved() method in the MouseMotionAdapter class handles the events generated by movement of a mouse.

The following table lists the various adapter classes:
Adapter Class Description

KeyAdapter

Provides empty implementation of the methods of the KeyListener interface, such as keyPressed(),

keyReleased(), and keyTyped() methods for receiving keyboard events MouseAdapter Provides empty implementation of the methods of the Mouse-Listener mousePressed(), interface, such as mouseClicked(), and

mouseExited(),

mouseEntered(),

mouseReleased() methods for receiving mouse events. MouseMotionAdapter Provides empty implementation of the methods of the MouseMotionListener interface, such as mouseDragged() and mouseMoved() methods for receiving mouse motion events. WindowAdapter Provides empty implementation of the methods of the WindowListener and WindowFocusListener interfaces,

such as windowActivated(),windowClosed(),windowClosing, windowOpened(), and windowGainedFocus() methods for receiving window events. FocusAdapter Provides empty implementation of the methods of the FocusListener interface, such as focusGained() and

focusLost () methods for receiving keyboard focus events.

Using the MouseAdapter Class
The MouseAdapter class provides empty implementation of mouse event-handling methods, such as mouseClicked(), mouseEntered(), mouseExited(),mousePressed(), and mouseReleased(). A class that acts as a listener for mouse events extends the MouseAdapter class and overrides the required methods.

The following code shows the use of the MouseAdapter class:

import javax.swing.*; import java.awt.*; import java.awt.event.*;

class adapterTest extends JFrame implements ActionListener { int X, Y; String str; JButton b; JLabel l;

public adapterTest() { super("The Mouse Adapter"); getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT)); JPanel p =new JPanel(); p.setLayout(new FlowLayout()); l = new JLabel(str + X + Y); getContentPane().add(l,"South"); b = new JButton("Quit"); b.addActionListener(this); p.add(b); getContentPane().add(p); ListenerClass listen = new ListenerClass(); addMouseListener(listen); setSize(300,300); setVisible(true); } public void actionPerformed(ActionEvent ae) { String s= ae.getActionCommand(); if ( "Quit".equals(s)) System.exit(0); }

public static void main(String args[]) { adapterTest f = new adapterTest(); } } class ListenerClass extends MouseAdapter { public void mouseClicked(MouseEvent me) { adapterTest AT; AT = (adapterTest)me.getSource(); AT.l.setText("Mouse clicked at:" + me.getX()+ "," +me.getY()); } }

In the preceding code, the adapterTest

class

extends

the

JFrame

class

and

implements the ActionListener interface. The constructor of adapterTest class creates an object, listen, of ListenerClass that extends the MouseAdapter class. The listen object is registered to receive the notifications of the mouse events.

The ListenerClass overrides the mouseClicked() method to handle the mouse event generated by the clicking of a mouse. As only mouseClicked() method is overridden by the Listener class therefore all the other mouse events, such as events by pressing and releasing a mouse, entering and exiting of a mouse in a component area are not handled. The output of the preceding code is:

Using Mouse Adapter Class

Using the MouseMotionAdapter Class
The MouseMotionAdpater class provides empty implementation of methods, such as mouseDragged() and mouseMoved(). A class that acts as a listener for mouse motion events extends the MouseAdapter class and overrides the required method.

The following code shows the use of the MouseMotionAdapter class:

import javax.swing.*; import java.awt.*; import java.awt.event.*;

class AdapterTestClass extends JFrame implements ActionListener { int X, Y; String str; JButton b; JLabel l; public AdapterTestClass() { super("The Mouse Motion Adapter"); getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT)); JPanel p =new JPanel(); p.setLayout(new FlowLayout()); l = new JLabel(str + X + Y); getContentPane().add(l,"South"); b = new JButton("Quit"); b.addActionListener(this); p.add(b); getContentPane ().add(p); ListenerClass listen = new ListenerClass(); addMouseMotionListener(listen); setSize(300,300); setVisible(true); }

public void actionPerformed(ActionEvent ae) { String s= ae.getActionCommand(); if (“Quit".equals(s)) System.exit(0); } public static void main(String args[]) { AdapterTestClass f = new AdapterTestClass(); } } class ListenerClass extends MouseMotionAdapter { public void mouseDragged(MouseEvent me) { AdapterTestClass AT; AT = (AdapterTestClass)me.getSource(); AT.l.setText("Mouse draggeded at:" + me.getX()+ "," + me.getY()); } } In the preceding code, AdapterTestClass extends the JFrame class and implements the ActionListener interface. The AdapterTestClass constructor creates an object, listen, of ListenerClass that extends the MouseMotionAdapter class. The listen object is registered to receive the notifications of the mouse motion events.

The ListenerClass overrides the mouseDragged() method to handle the mouse motion event generated by the dragging a mouse. As only mouseDragged() method is overridden by the ListenerClass therefore the mouse motion event generated by moving a mouse is not handled. The output of the preceding code is:

Using Mouse Adapter Class


								
To top