[Go to site: main page, start]

0% found this document useful (0 votes)
11 views27 pages

Java Event Handling in Linux Programming

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views27 pages

Java Event Handling in Linux Programming

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module IV Java Programing using Linux

4. EVENT HANDLING

Events are integral part of the java platform. It is an action or occurrence, often
generated by the user, to which the program might respond— An example of an event is
the user of a computer pressing a button on the screen. Another is the typing of any key
on the keyboard.

In traditional programming model, the application controls program flow. This flow is
predetermined by the statements and conditions that are coded.
Events do not adhere to this traditional approach because they occur outside of
program control. When an event happens, the application is notified, causing the
execution of a piece of code. Usually, this notification involves calling a predefined
procedure or function, passing it enough information to identify the event so that the
application can perform its logic.. Event-driven programming provides the means to
develop flexible applications where the user determines program flow.

The Delegation Event Model


The modern approach to handling events is based on the delegation event model,
which defines standard and consistent mechanisms to generate and process events. Here a
source generates an event and sends it to one or more listeners.
In this scheme, the listener simply waits until it receives an event. Once received,
the listener processes the event and then returns. The advantage of this design is that
the application logic that processes events is cleanly separated from the user interface
logic that generates those events.

In the delegation event model, listeners must register with a source in order
to receive an event notification. This provides an important benefit: notifications are
sent only to listeners that want to receive them. This is a more efficient way to handle
events.

Events

1
Module IV Java Programing using Linux

In the delegation model, an event is an object that describes a state change in a source. It
can be generated as a consequence of a person interacting with the elements in a graphical
user interface. Some of the activities that cause events to be generated are pressing a button,
entering a character via the keyboard, selecting an item in a list, and clicking the mouse

Event Sources
A source is an object that generates an event. This occurs when the internal
state of that object changes in some way. Sources may generate more than one type of
event. A source must register listeners in order for the listeners to receive notifications
about a specific type of event. Each type of event has its own registration method. Here
is the general form:

public void addTypeListener(TypeListener el)


Here, Type is the name of the event and el is a reference to the event listener. For
example, the method that registers a keyboard event listener is called addKeyListener( ).
When an event occurs, all registered listeners are notified and receive a copy of the event
object. This is known as multicasting the event. In all cases, notifications are sent only to
listeners that register to receive them

A source must also provide a method that allows a listener to unregister an


interest in a specific type of event. The general form of such a method is this:

public void removeTypeListener(TypeListener el)


For example, to remove a keyboard listener, you would call removeKeyListener( ).
The methods that add or remove listeners are provided by the source that generates
events. For example, the Component class provides methods to add and remove
keyboard and mouse event listeners.

Event Listeners
A listener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to receive
notifications about specific types of events. Second, it must implement methods to
receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces
found in [Link]. For example, the MouseMotionListener interface defines two
methods to receive notifications when the mouse is dragged or moved. Any object may
receive and process one or both of these events if it provides an implementation of this
interface.

Event Classes
The classes that represent events are at the core of Java’s event handling mechanism. At

2
Module IV Java Programing using Linux

the root of the Java event class hierarchy is EventObject, which is in [Link]. It is the superclass
for all events. Its one constructor is shown here:

EventObject(Object src)

Here, src is the object that generates this event. EventObject contains two
methods: getSource( ) and toString( ). The getSource( ) method returns the source of the
event. Its general form is shown here:
Object getSource( )

As expected, toString( ) returns the string equivalent of the event.

The class AWTEvent, defined within the [Link] package, is a subclass of


EventObject. It is the superclass (either directly or indirectly) of all AWT-based events.
used by the delegation event model. Its getID( ) method can be used to determine the type
of the event. The signature of this method is shown here:

int getID( )

(Fig : 4.1)

3
Module IV Java Programing using Linux

Event Listener Method Source


ActionEvent ActionListener void actionPerformed(ActionEvent ae) Button
(clicked),
List(Item
double
clicked)
AdjustmentEvent AdjustmentListener void adjustmentValueChanged(AdjustmentEvent ae) Scrollbar
ComponentEvent ComponentListener void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
ContainerEvent ContainerListener void componentAdded(ContainerEvent t ce) (Component
void componentRemoved(ContainerEvent t ce) added or
removed)
FocusEvent FocusListener void focusGained(FocusEvent fe) (Components
void focusLost(FocusEvent fe) gain or lost
focus)
ItemEvent ItemListener void itemStateChanged(ItemEvent ie) Checkbox
Choice(choice
Changed)
List(item
selected or
deselected)
Menu Item
TextEvent TextListener void textChanged(TextEvent te) Text
component(en
ter a
character)
KeyEvent KeyListener void keyPressed(KeyEvent ke) Keyboard
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
MouseEvent MouseListener void mouseClicked(MouseEvent me) Mouse
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
MouseEvent MouseMotionListene void mouseDragged(MouseEvent me)
r void mouseMoved(MouseEvent me)
MouseWheelEvent MouseWheelListener void mouseWheelMoved(MouseWheelEvent mwe)

WindowEvent WindowListener void windowActivated(WindowEvent we) Window


void windowDeactivated(WindowEvent we)
void windowOpened(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowIconified(WindowEvent we)
void windowDeiconified(WindowEvent we)
WindowEvent WindowFocusListene void windowGainedFocus(WindowEvent we)
r void windowLostFocus(WindowEvent we)

4
Module IV Java Programing using Linux

The table below shows main Event Classes in [Link]

Event Class Description


ActionEvent Generated when a button is pressed, a list item is double clicked, or a
menu item is selected
ComponentEvent Generated when a component is hidden, moved, resized, or becomes
visible

FocusEvent Generated when a component gains or losses keyboard focus


ItemEvent Generated when a check box or list item is clicked; also occurs when a
choice selection is made or a checkable menu item is selected or
deselected.
KeyEvent Generated when input is received from the keyboard
MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or
released; also generated when the mouse enters or exits a component.
MouseWheelEvent Generated when the mouse wheel is moved
WindowEvent Generated when a window is activated, closed, deactivated, deiconified,
iconified, opened, or quit.

The ActionEvent Class


An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a
menu item is selected. The ActionEvent class defines four integer constants that can be
used to identify any modifiers associated with an action event: ALT_MASK, CTRL_MASK,
META_MASK, and SHIFT_MASK. In addition, there is an integer constant,
ACTION_PERFORMED, which can be used to identify action events.
ActionEvent has these three constructors:
ActionEvent(Object src, int type, String cmd)

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


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

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

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

5
Module IV Java Programing using Linux

meanings are shown here:


COMPONENT_HIDDEN: the component is hidden.
COMPONENT_MOVED: the component is moved.
COMPONENT_RESIZE: the component is resized.
COMPONENT_SHOWN: the component becomes visible.

FocusEvent Class
A FocusEvent is generated when a component gains or loses input focus. These events
are identified by the integer constants FOCUS_GAINED and FOCUS_LOST. FocusEvent is a
subclass of ComponentEvent and has these constructors:
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, boolean temporaryFlag)
Focus Event(Component src, int type, boolean temporaryFlag, Component other)

Here, src is a reference to the component that generated this event. The type of the event is
specified by type. The argument temporaryFlag is set to true if the focus event is temporary.
Otherwise, it is set to false. (A temporary focus event occurs as a result of another user interface
operation. For example, assume that the focus is in a text field. If the user moves the mouse to
adjust a scroll bar, the focus is temporarily lost.) The other component involved in the focus
change, called the opposite component, is passed in other. Therefore, if a FOCUS_GAINED event
occurred, other will refer to the component that lost focus. Conversely, if a FOCUS_LOST event
occurred, other will refer to the component that gains focus.

ItemEvent class

An ItemEvent is generated when a check box or a list item is clicked or when a checkable
menu item is selected or deselected. There are two types of item events, which are identified by the
following integer constants:
DESELECTED The user deselected an item.
SELECTED The user selected an item.

In addition, ItemEvent defines one integer constant,


ITEM_STATE_CHANGED, that signifies a change of [Link] has this
constructor:
The KeyEvent Class
A KeyEvent is generated when keyboard input occurs. There are three types of key
events, which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED,
and KEY_TYPED. The first two events are generated when any key is pressed or released. The
last event occurs only when a character is generated. Remember, not all key presses result in
characters. For example, pressing the SHIFT key does not generate a character. KeyEvent is a

6
Module IV Java Programing using Linux

subclass of InputEvent. Here are two of its constructors:

KeyEvent(Component src, int type, long when, int modifiers, int code)

KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
Here, src is a reference to the component that generated the event. The type of the
event is specified by type. The system time at which the key was pressed is passed in when. The
modifiers argument indicates which modifiers were pressed when this key event occurred. The
virtual key code, such as VK_UP, VK_A, and so forth, is passed in code. The character
equivalent (if one exists) is passed in ch. If no valid character exists, then ch contains
CHAR_UNDEFINED. For KEY_TYPED events, code will contain VK_UNDEFINED

The MouseEvent Class


There are eight types of mouse events. The MouseEvent class defines the
following integer constants that can be used to identify them:

MOUSE_CLICKED The user clicked the mouse. MOUSE_DRAGGED The


user dragged the mouse. MOUSE_ENTERED The mouse entered a
component.
MOUSE_EXITED The mouse exited from a component.
MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed. MOUSE_RELEASED The
mouse was released. MOUSE_WHEEL The mouse wheel was moved
The MouseWheelEvent Class

The MouseWheelEvent class encapsulates a mouse wheel event. It is a subclass of


MouseEvent. If a mouse has a wheel, it is located between the left and right buttons. Mouse
wheels are used for scrolling. MouseWheelEvent defines these two integer constants.
WHEEL_BLOCK_SCROLL A page-up or page-down scroll event occurred.
WHEEL_UNIT_SCROLL A line-up or line-down scroll event occurred.

The WindowEvent Class


There are ten types of window events. The WindowEvent class defines integer
constants that can be used to identify them. The constants and their meanings are shown
here:

WINDOW_ACTIVATED The window was activated. WINDOW_CLOSED


The window has been closed. WINDOW_CLOSING
The user requested that the window be closed.

7
Module IV Java Programing using Linux

WINDOW_DEACTIVATED The window was deactivated.


WINDOW_DEICONIFIED The window was deiconified.
WINDOW_GAINED_FOCUS The window gained input focus.

WINDOW_ICONIFIED The window was iconified.


WINDOW_LOST_FOCUS The window lost input focus.
WINDOW_OPENED The window was opened.
WINDOW_STATE_CHANGED The state of the window changed.

Event Listener Interfaces


Listeners in delegation event model are created by implementing one or more of the
interfaces defined by the [Link] package. When an event occurs, the event source invokes
the appropriate method defined by the listener and provides an event object as its argument.
Following table lists commonly used listener interfaces.

Control Description
ActionListener This interface is used for receiving the action events.

ComponentListener This interface is used for receiving the component events.

ItemListener This interface is used for receiving the item events.

KeyListener This interface is used for receiving the key events.

MouseListener This interface is used for receiving the mouse events.

TextListener This interface is used for receiving the text events.

WindowListener This interface is used for receiving the window events.

AdjustmentListener This interface is used for receiving the adjusmtent events.

ContainerListener This interface is used for receiving the container events.

MouseMotionListener This interface is used for receiving the mouse motion events.

FocusListener This interface is used for receiving the focus events.

8
Module IV Java Programing using Linux

The ActionListener Interface


This interface defines the actionPerformed( ) method that is invoked when an action
event occurs. Its general form is shown here:
void actionPerformed(ActionEvent ae)
The ComponentListener Interface

This interface defines four methods that are invoked when a component is resized,
moved, shown, or hidden. Their general forms are shown here:
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
The FocusListener Interface
This interface defines two methods. When a component obtains keyboard focus,
focusGained() is invoked. When a component loses keyboard focus, focusLost( ) is called. Their
general forms are shown here:

void focusGained(FocusEvent fe)


void focusLost(FocusEvent Fe)

The ItemListener Interface


This interface defines the itemStateChanged( ) method that is invoked when the state of
an item changes. Its general form is shown here:
void itemStateChanged(ItemEvent ie)

The KeyListener Interface


This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are
invoked when a key is pressed and released, respectively. The keyTyped( ) method is invoked
when a character has been entered.
For example, if a user presses and releases the A key, three events are generated in
sequence: key pressed, typed, and released. If a user presses and releases the HOME key, two
key events are generated in sequence: key pressed and released.
The general forms of these methods are shown here:
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke) void
keyTyped(KeyEvent ke)

9
Module IV Java Programing using Linux

The MouseListener Interface


This interface defines five methods. If the mouse is pressed and released at the same
point, mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( )
method is called. When it leaves, mouseExited( ) is called. The mousePressed( ) and
mouseReleased( ) methods are invoked when the mouse is pressed and released, respectively.
The general forms of these methods are shown here:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)

The MouseMotionListener Interface


This interface defines two methods. The mouseDragged( ) method is called multiple
times as the mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse
is moved. Their general forms are shown here:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)

The MouseWheelListener Interface


This interface defines the mouseWheelMoved( ) method that is invoked when the
mouse wheel is moved. Its general form is shown here.
void mouseWheelMoved(MouseWheelEvent mwe)
The WindowListener Interface
This interface defines seven methods. The windowActivated( ) and windowDeactivated( )
methods are invoked when a window is activated or deactivated, respectively. If a window is
iconified, the windowIconified( ) method is called. When a window is deiconified, the
windowDeiconified( ) method is called. When a window is opened or closed, the windowOpened(
) or windowClosed( ) methods are called, respectively. The windowClosing( ) method is
called when a window is being closed. The general forms of these methods
are
void windowActivated(WindowEvent we) void
windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)

ADAPTER CLASS

10
Module IV Java Programing using Linux

Java provides a special feature, called an adapter class, that can simplify the creation of
event handlers in certain situations. An adapter class provides an empty implementation of all
methods in an event listener interface. Adapter classes are useful when you want to receive and
process only some of the events that are handled by a particular event listener interface. You can
define a new class to act as an event listener by extending one of the adapter classes and
implementing only those events in which you are interested.

For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ). The signatures of these empty methods are exactly as defined in the
MouseMotionListener interface. If you were interested in only mouse drag events, then you could
simply extend MouseMotionAdapter and implement mouseDragged().The empty implementation
of mouseMoved( ) would handle the mouse motion events for you.
For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ). The signatures of these empty methods are exactly as defined in the
MouseMotionListener interface. If you were interested in only mouse drag events, then you
could simply extend MouseMotionAdapter and implement mouseDragged().The empty
implementation of mouseMoved( ) would handle the mouse motion events for you.

Adapter Class Listener Interface

Component Adapter ComponentListener

ContainerAdapter ContainerListener

MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener

KeyAdapter KeyListener

FocusAdapter FocusListener

Java AWT

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based


applications in java.

Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavyweight i.e. its components are using the resources
of OS.

11
Module IV Java Programing using Linux

The [Link] package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.

Container

The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.

Window

The window is the container that have no borders and menu bars. You must use frame,
dialog or another window for creating a window.

Panel

The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.

Frame

The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

12
Module IV Java Programing using Linux

Useful Methods of Component class

Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by
default false.
Java Swing

Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The [Link] package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing


1) AWT components are platform-dependent. Java swing components are platform-
independent.
2) AWT components are heavyweight. Swing components are lightweight.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and
feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
5) AWT doesn't follows MVC(Model View Swing follows MVC.
Controller) where model represents data, view
represents presentation and controller acts as an
interface between model and view.

13
Module IV Java Programing using Linux

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.

Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.

Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int sets size of the component.
height)
public void setLayout(LayoutManager sets the layout manager for the component.
m)
public void setVisible(boolean b) sets the visibility of the component. It is by default
false.

14
Module IV Java Programing using Linux

import [Link].*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


[Link](130,100,100, 40);//x axis, y axis, width, height
[Link](b);//adding button in JFrame

[Link](400,500);//400 width and 500 height


[Link](null);//using no layout managers
[Link](true);//making the frame visible
}
}

Java JButton

The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.

Commonly used Constructors:


Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:


Methods Description
void setText(String s) It is used to set specified text on button
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.

15
Module IV Java Programing using Linux

void setIcon(Icon b) It is used to set the specified Icon on the button.


Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void It is used to add the action listener to this object.
addActionListener(ActionListener a)
import [Link].*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
[Link](50,100,95,30);
[Link](b);
[Link](400,400);
[Link](null);
[Link](true);
}
}

Java JLabel

The object of JLabel class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but a user
cannot edit it directly. It inherits JComponent class.

Commonly used Constructors:


Constructor Description
JLabel() Creates a JLabel instance with no image and with an empty string
for the title.
JLabel(String s) Creates a JLabel instance with the specified text.
JLabel(Icon i) Creates a JLabel instance with the specified image.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.

16
Module IV Java Programing using Linux

Commonly used Methods:


Methods Description
String getText() t returns the text string that a label displays.
void setText(String text) It defines the single line of text this component will
display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along the X
alignment) axis.
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the X
axis.
Java JTextField

The object of a JTextField class is a text component that allows the editing of a single
line text. It inherits JTextComponent class.

Commonly used Constructors:

Constructor Description
JTextField() Creates a new TextField
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.
JTextField(int columns) Creates a new empty TextField with the specified number of
columns.

Commonly used Methods:

Methods Description
void addActionListener(ActionListener l) It is used to add the specified action listener to
receive action events from this textfield.
Action getAction() It returns the currently set Action for this
ActionEvent source, or null if no Action is set.
void setFont(Font f) It is used to set the current font.
void removeActionListener(ActionListener l) It is used to remove the specified action listener
so that it no longer receives action events from
this textfield.
Java JTextArea

The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class

17
Module IV Java Programing using Linux

Constructor Description
JTextArea() Creates a text area that displays no text initially.
JTextArea(String s) Creates a text area that displays specified text initially.
JTextArea(int row, int column) Creates a text area with the specified number of rows and
columns that displays no text initially.
JTextArea(String s, int row, int Creates a text area with the specified number of rows and
column) columns that displays specified text.

Methods Description
void setRows(int rows) It is used to set specified number of rows.
void setColumns(int cols) It is used to set specified number of columns.
void setFont(Font f) It is used to set the specified font.
void insert(String s, int It is used to insert the specified text on the specified position.
position)
void append(String s) It is used to append the given text to the end of the document.

Java JCheckBox

The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.

Constructor Description
JJCheckBox() Creates an initially unselected check box button
with no text, no icon.
JChechBox(String s) Creates an initially unselected check box with text.
JCheckBox(String text, boolean selected) Creates a check box with text and specifies whether
or not it is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken
from the Action supplied.

Methods Description
AccessibleContext It is used to get the AccessibleContext associated with this
getAccessibleContext() JCheckBox.
protected String paramString() It returns a string representation of this JCheckBox.
Java JRadioButton

18
Module IV Java Programing using Linux

The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.

Constructor Description
JRadioButton() Creates an unselected radio button with no text.
JRadioButton(String s) Creates an unselected radio button with specified text.
JRadioButton(String s, boolean Creates a radio button with the specified text and selected
selected) status.

Commonly used Methods:

Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void It is used to add the action listener to this object.
addActionListener(ActionListener a)
Java JComboBox

The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.

Commonly used Constructors:


Constructor Description
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the
specified array.
JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the
specified Vector.

Commonly used Methods:

Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.

19
Module IV Java Programing using Linux

void removeAllItems() It is used to remove all the items from the


list.
void setEditable(boolean b) It is used to determine whether the
JComboBox is editable.
void addActionListener(ActionListener a) It is used to add the ActionListener.
void addItemListener(ItemListener i) It is used to add the ItemListener.
Java JList

The object of JList class represents a list of text items. The list of text items can be set up so that
the user can choose either one item or multiple items. It inherits JComponent class.

Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> Creates a JList that displays elements from the specified, non-null,
dataModel) model.

Commonly used Methods:


Methods Description
Void It is used to add a listener to the list, to be
addListSelectionListener(ListSelectionListener notified each time a change to the selection
li) occurs.
int getSelectedIndex() It is used to return the smallest selected cell
index.
ListModel getModel() It is used to return the data model that holds a
list of items displayed by the JList
component.
void setListData(Object[] listData) It is used to create a read-only ListModel
from an array of objects.
Java JFrame

The [Link] class is a type of container which inherits the [Link] class.
JFrame works like the main window where components like labels, buttons, textfields are added
to create a GUI.

Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.

20
Module IV Java Programing using Linux

Nested Class
Modifier and Type Class Description
protected class [Link] This class implements accessibility support
for the JFrame class.

Fields
Modifier and Type Field Description
protected accessibleContext The accessible context property.
AccessibleContext
static int EXIT_ON_CLOSE The exit application default window close
operation.
protected rootPane The JRootPane instance that manages the
JRootPane contentPane and optional menuBar for this
frame, as well as the glassPane.
protected boolean rootPaneCheckingEnab If true then calls to add and setLayout will be
led forwarded to the contentPane.

Constructors

Constructor Description
JFrame() It constructs a new frame that is initially invisible.
JFrame(GraphicsConfiguration gc) It creates a Frame in the specified
GraphicsConfiguration of a screen device and a blank
title.
JFrame(String title) It creates a new, initially invisible Frame with the
specified title.
JFrame(String title, It creates a JFrame with the specified title and the
GraphicsConfiguration gc) specified GraphicsConfiguration of a screen device.
Java JPanel

The JPanel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the JComponents class.

It doesn't have title bar.

Commonly used Constructors:


Constructor Description
JPanel() It is used to create a new JPanel with a double buffer and

21
Module IV Java Programing using Linux

a flow layout.
JPanel(boolean isDoubleBuffered) It is used to create a new JPanel with FlowLayout and the
specified buffering strategy.
JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout
manager.

Java LayoutManagers

The LayoutManagers are used to arrange components in a particular manner. LayoutManager is


an interface that is implemented by all the classes of layout managers. The layout managers are:

1. BorderLayout 4. CardLayout
2. FlowLayout 5. Box Layout
3. GridLayout
Java FlowLayout

The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is
the default layout of applet or panel.

Fields of FlowLayout class


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class


1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

import [Link].*; f=new JFrame();


import [Link].*;
public class MyFlowLayout{ JButton b1=new JButton("1");
JFrame f; JButton b2=new JButton("2");
MyFlowLayout(){ JButton b3=new JButton("3");

22
Module IV Java Programing using Linux

JButton b4=new JButton("4"); [Link](b3);


JButton b5=new JButton("5"); [Link](b4);
[Link](b5);
[Link](b1); [Link](new FlowLayout(FlowLayo
[Link](b2); [Link]));
//setting flow layout of right alignment
[Link](300,300);
[Link](true);
}
public static void main(String[] args) {
new MyFlowLayout();
} }
Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:

o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.

import [Link].*; JButton b3=new JButton("EAST");;


import [Link].*; JButton b4=new JButton("WEST");;
public class Border JButton b5=new JButton("CENTER");
{ [Link](b1,[Link]);
JFrame f; [Link](b2,[Link]);
Border(){ [Link](b3,[Link]);
f=new JFrame(); [Link](b4,[Link]);
JButton b1=new JButton("NORTH" [Link](b5,[Link]);
);; [Link](300,300);
JButton b2=new JButton("SOUTH");; [Link](true);
}

23
Module IV Java Programing using Linux

public static void main(String[] args)


{
new Border();
} }

Java GridLayout

The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.

Constructors of GridLayout class


1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.

import [Link].*;
import [Link].*; [Link](b1); [Link](b2); [Link](b3);
[Link](b4); [Link](b5);
public class MyGridLayout{ [Link](b6); [Link](b7); [Link](b8);
JFrame f; [Link](b9);
MyGridLayout(){
f=new JFrame(); [Link](new GridLayout(3,3));
JButton b1=new JButton("1"); //setting grid layout of 3 rows and 3 col
JButton b2=new JButton("2"); umns
JButton b3=new JButton("3"); [Link](300,300);
JButton b4=new JButton("4"); [Link](true);
JButton b5=new JButton("5"); }
JButton b6=new JButton("6"); public static void main(String[] args) {
JButton b7=new JButton("7"); new MyGridLayout();
JButton b8=new JButton("8"); }
JButton b9=new JButton("9"); }

24
Module IV Java Programing using Linux

Java BoxLayout

The BoxLayout is used to arrange the components either vertically or horizontally. For this
purpose, BoxLayout provides four constants. They are as follows:

Fields of BoxLayout class


1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS

Constructor of BoxLayout class


1. BoxLayout(Container c, int axis): creates a box layout that arranges the components
with the given axis.

Example of BoxLayout class with Y-AXIS:


import [Link].*; setSize(400,400);
import [Link].*; setVisible(true);
}
public class BoxLayoutExample1 extends Fra public static void main(String args[]){
me { BoxLayoutExample1 b=new BoxLayoutExample1();
Button buttons[]; } }
public BoxLayoutExample1 () {
buttons = new Button [5];
for (int i = 0;i<5;i++) {
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setLayout (new BoxLayout (this, BoxLayout.
Y_AXIS));

25
Module IV Java Programing using Linux

Example of BoxLayout class with X-AXIS


import [Link].*; }
import [Link].*; public static void main(String args[]){
BoxLayoutExample2 b=new BoxLayoutExampl
public class BoxLayoutExample2 extends Fra e2();
me { }
Button buttons[]; }
public BoxLayoutExample2() {
buttons = new Button [5];
for (int i = 0;i<5;i++) {
buttons[i] = new Button ("Button " + (i + 1))
;
add (buttons[i]);
}
setLayout (new BoxLayout(this, BoxLayout.X
_AXIS));
setSize(400,400);
setVisible(true);
Java CardLayout

The CardLayout class manages the components in such a manner that only one component is
visible at a time. It treats each component as a card that is why it is known as CardLayout.

Constructors of CardLayout class


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.

Commonly used methods of CardLayout class


o public void next(Container parent): is used to flip to the next card of the given
container.

26
Module IV Java Programing using Linux

o public void previous(Container parent): is used to flip to the previous card of the given
container.
o public void first(Container parent): is used to flip to the first card of the given
container.
o public void last(Container parent): is used to flip to the last card of the given container.
o public void show(Container parent, String name): is used to flip to the specified card
with the given name.

Example of CardLayout class


import [Link].*;
import [Link].*;
import [Link].*;
public class CardLayoutExample extends JFrame implements ActionListener
{
CardLayout card; { [Link](c); }
JButton b1,b2,b3; public static void main(String[] args) {
Container c; CardLayoutExample cl=new CardLayoutE
CardLayoutExample() xample();
{ [Link](400,400);
c=getContentPane(); [Link](true);
card=new CardLayout(40,30); [Link](EXIT_ON_C
//create CardLayout object with 40 hor space an LOSE);
d 30 ver space }
[Link](card); }
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
[Link](this);
[Link](this);
[Link](this);
[Link]("a",b1);
[Link]("b",b2);
[Link]("c",b3);
}
public void actionPerformed(ActionEvent e)

27

You might also like