Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

java

The document explains the concept of CLASSPATH in Java, detailing its importance for locating required files by the Java Compiler and JVM, and provides instructions for setting it in Windows. It also discusses the differences between checked and unchecked exceptions in Java, as well as the exception specification and hierarchy. Additionally, the document covers multiprocessing versus multithreading, and introduces Java Swing, highlighting its advantages over AWT and providing examples of Swing programs.

Uploaded by

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

java

The document explains the concept of CLASSPATH in Java, detailing its importance for locating required files by the Java Compiler and JVM, and provides instructions for setting it in Windows. It also discusses the differences between checked and unchecked exceptions in Java, as well as the exception specification and hierarchy. Additionally, the document covers multiprocessing versus multithreading, and introduces Java Swing, highlighting its advantages over AWT and providing examples of Swing programs.

Uploaded by

Udaya CS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 64

CLASSPATH describes the location where all the required files are available which are used

in the application. Java Compiler and JVM (Java Virtual Machine) use CLASSPATH to locate
the required files. If the CLASSPATH is not set, Java Compiler will not be able to find the
required files and hence will throw the following error.

Error: Could not find or load main class <class name> (e.g.
GFG)

The above error is resolved when CLASSPATH is set.

Set the CLASSPATH in JAVA in Windows

Command Prompt:
set PATH=.;C:\Program Files\Java\JDK1.6.20\bin
Note: Semi-colon (;) is used as a separator and dot (.) is the default value of CLASSPATH in
the above command.

GUI:

1. Select Start
2. Go to the Control Panel

3. Select System and Security


4. Select Advanced System settings

5. Click on Environment Variables


6. Click on New under System Variables
7. Add CLASSPATH as variable name and path of files as a variable value.

8. Select OK.

Differences between Checked and Unchecked


Exceptions
Checked exceptions and unchecked exceptions.

An exception in Java is a spontaneous event that occurs during the runtime that can interrupt the regular flow of the
program. There are two types of exceptions:

1. Checked exceptions
2. Unchecked exceptions
What is a Checked Exception?

A checked exception is an exception that should be reported in the method in which it is thrown.

What is an Unchecked Exception?

An exception that occurs at the runtime or at the time of execution is known as an unchecked exception.

Differences between Checked and Unchecked Exceptions


in Java
S.No. Checked Exception Unchecked Exception

Checked exceptions happen at compile time Unchecked exceptions happen at


when the source code is transformed into an runtime when the executable
1. executable code. program starts running.

The checked exception is checked by the These types of exceptions are not
2. compiler. checked by the compiler.

3. Checked exceptions can be created manually. They can also be created manually.

This exception happens in runtime,


This exception is counted as a sub-class of and hence it is not included in the
4. the class. exception class.

Java Virtual Machine does not need


Java Virtual Machine requires the exception the exception to be caught or
5. to to be caught or handled. handled.
The exception specification

In Java, you’re required to inform the client programmer, who calls your method, of the
exceptions that might be thrown from your method. This is civilized, because the caller can
know exactly what code to write to catch all potential exceptions. Of course, if source code is
available, the client programmer could hunt through and look for throw statements, but often a
library doesn’t come with sources. To prevent this from being a problem, Java provides syntax
(and forces you to use that syntax) to allow you to politely tell the client programmer what
exceptions this method throws, so the client programmer can handle them. This is the exception
specification, and it’s part of the method declaration, appearing after the argument list. Comment

The exception specification uses an additional keyword, throws, followed by a list of all the
potential exception types. So your method definition might look like this:

void f() throws TooBig, TooSmall, DivZero { //...

If you say

void f() { // ...

it means that no exceptions are thrown from the method. (Except for the exceptions of
type RuntimeException, which can reasonably be thrown anywhere—this will be described
later.) Comment

You can’t lie about an exception specification—if your method causes exceptions and doesn’t
handle them, the compiler will detect this and tell you that you must either handle the exception
or indicate with an exception specification that it may be thrown from your method. By
enforcing exception specifications from top to bottom, Java guarantees that exception correctness
can be ensured at compile-time[54]. Comment

There is one place you can lie: you can claim to throw an exception that you really don’t. The
compiler takes your word for it, and forces the users of your method to treat it as if it really does
throw that exception. This has the beneficial effect of being a placeholder for that exception, so
you can actually start throwing the exception later without requiring changes to existing code.
It’s also important for creating abstract base classes and interfaces whose derived classes or
implementations may need to throw exceptions.
Java exceptions Hierarchy explained

Exceptions Hierarchy in Java

The hierarchy of Exceptions in the Java programming language begins with the Throwable
class – which comes from the Object class and is its direct subclasswhileThe Exception
class presents all This Throwable class further branches into two subclasses – Error and
Exception. Here’s a flowchart to understand the Java Exception hierarchy better:

The Exception class presents all the Exceptions that you might need to handle while
working with the Java programming language. Some commonly known and encountered
examples of such Exceptions include NullPointerException, ClassNotFoundException,
IllegalArgumentException, etc.

On the other hand, the Error class takes care of more severe problems in your Java
program architecture and is not taken care of within the application code. Exception
hierarchy in java with examples of errors are InternalError, AssertionError,
OutOfMemoryError, etc.

Unit 4:

Difference between Multiprocessing and Multithreading


DifferencesComputersSoftware & Coding

Both multiprocessing and multithreading are used in computer operating systems to increase its
computing power. The fundamental difference between multiprocessing and multithreading is that

multiprocessing makes the use of two or more CPUs to increase the computing power of the system,
while multithreading creates multiple threads of a process to be executed in a parallel fashion to
increase the throughput of the system.

What is Multiprocessing?
Multiprocessing refers to using multiple CPUs/processors in a single system. Multiple CPUs can act in
a parallel fashion and execute multiple processes together. A task is divided into multiple processes
that run on multiple processors. When the task is over, the results from all processors are compiled
together to provide the final output. Multiprocessing increases the computing power to a great extent.
Symmetric multiprocessing and asymmetric multiprocessing are two types of multiprocessing.

Multiprocessing increases the reliability of the system because of the use of multiple CPUs. However, a
significant amount of time and specific resources are required for multiprocessing. Multiprocessing is
relatively more cost effective as compared to a single CPU system.
What is Multithreading?
Multithreading refers to multiple threads being executed by a single CPU in such a way that each
thread is executed in parallel fashion and CPU/processor is switched between them using context
switch. Multithreading is a technique to increase the throughput of a processor. In multithreading,
accessing memory addresses is easy because all of the threads share the same parent process.

The switching among different threads is fast and efficient. It must be noted that in multithreading,
multiple threads are created from a single process and then these threads are processed
simultaneously.

Difference between Multiprocessing and Multithreading

The following table highlights the major differences between Multiprocessing and Multithreading −

Factor Multiprocessing Multithreading

Multiple threads are created


Multiple processors/CPUs
of a process to be executed
are added to the system
Concept in a parallel fashion to
to increase the computing
increase the throughput of
power of the system.
the system.

Multiple processes are Multiple threads are


Parallel
executed in a parallel executed in a parallel
Action
fashion. fashion.

Multiprocessing can be
classified into symmetric No such classification
Categories
and asymmetric present for multithreading.
multiprocessing.

Process creation is time- Thread creation is easy and


Time
consuming. is time savvy.

In multiprocessing, many In multithreading, many


Execution processes are executed threads are executed
simultaneously. simultaneously.

In multiprocessing, a In multithreading, a
Address
separate address space is common address space is
space
created for each process. used for all the threads.

Resources Multiprocessing requires a Multithreading requires less


significant amount of time time and few resources to
and large number of
create.
resources.

Unit – 5

Introduction to Java Swing


Last Updated : 30 Jul, 2024
Generative Summary

Now you can generate the summary of any article of your choice.

Got it



Swing is a Java Foundation Classes [JFC] library and an extension of the


Abstract Window Toolkit [AWT]. Java Swing offers much-improved
functionality over AWT, new components, expanded components features,
and excellent event handling with drag-and-drop support.
Introduction of Java Swing
Swing has about four times the number of User Interface [UI] components as
AWT and is part of the standard Java distribution. By today’s application GUI
requirements, AWT is a limited implementation, not quite capable of
providing the components required for developing complex GUIs required in
modern commercial applications. The AWT component set has quite a few
bugs and does take up a lot of system resources when compared to
equivalent Swing resources. Netscape introduced its Internet Foundation
Classes [IFC] library for use with Java. Its Classes became very popular with
programmers creating GUI’s for commercial applications.
 Swing is a Set of API (API- Set of Classes and Interfaces)
 Swing is Provided to Design Graphical User Interfaces
 Swing is an Extension library to the AWT (Abstract Window Toolkit)
 Includes New and improved Components that have been enhancing the
looks and Functionality of GUIs’
 Swing can be used to build (Develop) The Standalone swing GUI Apps as
Servlets and Applets
 It Employs model/view design architecture.
 Swing is more portable and more flexible than AWT, the Swing is built on
top of the AWT.
 Swing is Entirely written in Java.
 Java Swing Components are Platform-independent, and The Swing
Components are lightweight.
 Swing Supports a Pluggable look and feel and Swing provides more
powerful components.
 such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.
 Further Swing Follows MVC.
Difference between Java Swing and Java AWT
There are certain points from which Java Swing is different than Java AWT as
mentioned below:

Java AWT Java Swing


Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes and
applications in Java. is used to create various applications.

The components of Java Swing are


Components of AWT are heavy weighted.
lightweight.

Components are platform dependent. Components are platform independent.

Execution Time is more than Swing. Execution Time is less than AWT.

Swing components requires javax.swing


AWT components require java.awt package.
package.

The MVC Connection


 In general, a visual component is a composite of three distinct aspects:
1. The way that the component looks when rendered on the screen.
2. The way such that the component reacts to the user.
3. The state information associated with the component.
 Over the years, one component architecture has proven itself to be
exceptionally effective: – Model-View-Controller or MVC for short.
 In MVC terminology, the model corresponds to the state information associated
with the Component.
 The view determines how the component is displayed on the screen, including
any aspects of the view that are affected by the current state of the model.
 The controller determines how the component reacts to the user.
The simplest Swing components have capabilities far beyond AWT
components as follows:
 Swing buttons and labels can be displaying images instead of or in addition to
text.
 The borders around most Swing components can be changed easily. For
example, it is easy to put a 1-pixel border around the outside of a Swing label.
 Swing components do not have to be rectangular. Buttons, for example, can be
round.
 Now The Latest Assertive technologies such as screen readers can easily get
information from Swing components. Example: A screen reader tool can easily
capture the text that is displayed on a Swing button or label.

Example of Java Swing Programs


Example 1: Develop a program using label (swing) to display the message “GFG WEB
Site Click”:
Java

// Java program using label (swing)


// to display the message “GFG WEB Site Click”
import java.io.*;
import javax.swing.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating instance of JFrame
JFrame frame = new JFrame();

// Creating instance of JButton


JButton button = new JButton(" GFG WebSite Click");

// x axis, y axis, width, height


button.setBounds(150, 200, 220, 50);

// adding button in JFrame


frame.add(button);

// 400 width and 500 height


frame.setSize(500, 600);

// using no layout managers


frame.setLayout(null);

// making the frame visible


frame.setVisible(true);
}
}
Output:

Example 2: Write a program to create three buttons with caption OK, SUBMIT, CANCEL.
Java

// Java program to create three buttons


// with caption OK, SUBMIT, CANCEL
import java.awt.*;

class button {
button()
{
Frame f = new Frame();

// Button 1 created
// OK button
Button b1 = new Button("OK");
b1.setBounds(100, 50, 50, 50);
f.add(b1);

// Button 2 created
// Submit button
Button b2 = new Button("SUBMIT");
b2.setBounds(100, 101, 50, 50);
f.add(b2);

// Button 3 created
// Cancel button
Button b3 = new Button("CANCEL");
b3.setBounds(100, 150, 80, 50);
f.add(b3);

f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}

public static void main(String a[]) { new button(); }


}
Output:

Components of Swing Class the task’s percentage


Class Description

A Component is the Abstract base class for about the


non-menu user-interface controls of Java SWING.
Component
Components are representing an object with a
graphical representation.

A Container is a component that can container Java


Container
SWING Components

A JComponent is a base class for all swing UI


Components In order to use a swing component that
JComponent inherits from JComponent, the component must be in
a containment hierarchy whose root is a top-level
Java Swing container.

A JLabel is an object component for placing text in a


JLabel
container.

JButton This class creates a labeled button.


Class Description

A JColorChooser provides a pane of controls


JColorChooser designed to allow the user to manipulate and select a
color.

A JCheckBox is a graphical (GUI) component that


JCheckBox
can be in either an on-(true) or off-(false) state.

The JRadioButton class is a graphical (GUI)


JRadioButton component that can be in either an on-(true) or off-
(false) state. in the group

A JList component represents the user with the


JList
scrolling list of text items.

A JComboBox component is Presents the User with a


JComboBox
show up Menu of choices.

A JTextField object is a text component that will


JTextField
allow for the editing of a single line of text.

A JPasswordField object it is a text component


JPasswordField
specialized for password entry.

A JTextArea object is a text component that allows


JTextArea
for the editing of multiple lines of text.

A ImageIcon control is an implementation of the


Imagelcon
Icon interface that paints Icons from Images
Class Description

A JScrollbar control represents a scroll bar


JScrollbar component in order to enable users to Select from
range values.

JOptionPane provides set of standard dialog boxes


JOptionPane
that prompt users for a value or Something.

A JFileChooser it Controls represents a dialog


JFileChooser
window from which the user can select a file.

As the task progresses towards completion, the


JProgressBar progress bar displays the tasks percentage on its
completion.

A JSlider this class is letting the user graphically


JSlider (GUI) select by using a value by sliding a knob
within a bounded interval.

A JSpinner this class is a single line input where the


JSpinner field that lets the user select by using a number or an
object value from an ordered sequence.
java Swing is a popular framework for creating Graphical User Interfaces (GUI) in
Java. It is a part of the Java Foundation Classes (JFC) and is widely used for
developing desktop applications.

What is Java Swing?

Java Swing is a popular and powerful Graphical User Interface (GUI) toolkit that is
used for developing desktop applications. It is a part of the Java Foundation Classes
(JFC) and provides a rich set of components and layout managers for creating a
variety of GUIs. Java Swing is platform-independent and can be used on any
operating system that supports Java.

It provides a set of lightweight components that are not only easy to use but also
customizable. Some of the commonly used components in Swing are buttons, text
fields, labels, menus, and many more.

Java Swing provides a pluggable look and feels that allows developers to customize
the GUI according to the user’s preferences. It also provides a robust event-handling
mechanism that allows developers to handle events generated by the graphical
components.

Some of the commonly used layout managers in Java Swing are BorderLayout,
FlowLayout, GridLayout, CardLayout, and BoxLayout. These layout managers allow
developers to create complex and intuitive GUIs that are easy to use and navigate.

Features of Java Swing

Some of the notable features of Java Swing are:

1. Platform Independence: Platform independence is one of Java Swing’s most


remarkable features. It can run on any platform that supports Java. Thus, Swing-
based applications can run on Windows, Mac, Linux, or any other Java-compatible
operating system.
2. Lightweight Components: Java Swing provides a set of lightweight components
that are easy to use and customizable. These components are designed to consume
less memory and use less processing power, making Swing-based applications run
efficiently.
3. Pluggable Look and Feel: Java Swing provides a pluggable look and feels that
allows developers to customize the appearance of the GUI according to the user’s
preferences. Developers can choose from several pre-built looks and feel themes or
create their own custom themes.
4. Layout Managers: Java Swing provides a set of layout managers that can be used
to organize the graphical components in a GUI. These layout managers enable
developers to create flexible and responsive GUIs that adapt to different screen
sizes and resolutions.
5. Robust Event Handling Mechanism: Java Swing provides a robust event handling
mechanism that allows developers to handle events generated by the graphical
components. Developers can register event listeners to detect and respond to user
interactions with the GUI.

Java Swing Class Hierarchy

The Java Swing API hierarchy is shown below:

Java Swing Packages

Some of the commonly used packages in Java Swing are:

1. javax.swing: This package contains the core components of Swing, such as


JButton, JLabel, JTable, JList, and many more. It also contains the classes for
creating top-level containers such as JFrame and JDialog.
2. javax.swing.event: This package contains the classes for handling events
generated by the Swing components. It includes event listener interfaces, event
adapter classes, and event objects.
3. javax.swing.border: This package contains classes for creating borders around the
Swing components. It includes the classes for creating line borders, etched borders,
and titled borders.
4. javax.swing.layout: This package contains the classes for creating and managing
layout managers in Swing. It includes the commonly used layout managers such as
BorderLayout, FlowLayout, GridLayout, BoxLayout, and CardLayout.
5. javax.swing.plaf: This package contains the classes for the pluggable look and
feels feature of Swing. It includes the classes for creating and managing the look
and feel themes, and also provides the default look and feel theme for each
platform.
6. javax.swing.text: This package contains the classes for creating and managing text
components in Swing. It includes classes for creating text fields, text areas, and
other text-related components.
7. javax.swing.table: This package contains the classes for creating and managing
tables in Swing. It includes the classes for creating JTable, TableModel,
TableColumn, and TableCellRenderer.

Components of Java Swing

Some of the important and common components of the Java Swing class are:

1. JFrame: JFrame is a top-level container that represents the main window of a GUI
application. It provides a title bar, and minimizes, maximizes, and closes buttons.
2. JPanel: JPanel is a container that can hold other components. It is commonly used
to group related components together.
3. JButton: JButton is a component that represents a clickable button. It is commonly
used to trigger actions in a GUI application.
4. JLabel: JLabel is a component that displays text or an image. It is commonly used
to provide information or to label other components.
5. JTextField: JTextField is a component that allows the user to input text. It is
commonly used to get input from the user, such as a name or an address.
6. JCheckBox: JCheckBox is a component that represents a checkbox. It is commonly
used to get a binary input from the user, such as whether or not to enable a feature.
7. JList: JList is a component that represents a list of elements. It is typically used to
display a list of options from which the user can select one or more items.
8. JTable: JTable is a component that represents a data table. It is typically used to
present data in a tabular fashion, such as a list of products or a list of orders.
9. JScrollPane: JScrollPane is a component that provides scrolling functionality to
other components. It is commonly used to add scrolling to a panel or a table.

Difference between Java Swing and Java AWT

Here is a comparison of Java Swing and Java AWT:

Feature Java Swing Java AWT

Platform-
Architecture Platform-Dependent
Independent

Pluggable look and


Look and Feel Native look and feel
feel

Richer set of Basic set of


Components
components components

Slower due to Faster due to native


Performance
software rendering OS rendering

More flexible and Simpler and less


Event Model
powerful powerful

By default, it is not
Thread Safety Thread-safe by default
thread-safe

Customization Highly customizable Less customizable


Feature Java Swing Java AWT

More layout Fewer layout


Layout
managers are managers are
Managers
available available

Extensive API with Basic API with fewer


API
many features features

Graphics It supports more It only supports basic


Support advanced graphics graphics

Size is small due to


Size is large due to
File Size fewer APIs and
additional APIs
classes

Containers - Java Swing


Containers are an integral part of SWING GUI components. A container provides a

space where a component can be located. A Container in AWT is a component itself

and it provides the capability to add a component to itself. Following are certain

noticable points to be considered.

 Sub classes of Container are called as Container. For example, JPanel, JFrame and

JWindow.

 Container can add only a Component to itself.

 A default layout is present in each container which can be overridden using

setLayout method.
SWING Containers

Following is the list of commonly used containers while designing GUI using SWING.

1. Panel: JPanel is the simplest container. It provides space in which any other

component can be placed, including other panels.

2. Frame: A JFrame is a top-level window with a title and a border.

3. Window: A JWindow object is a top-level window with no borders and no menubar.

Introduction-JPanel:

The class JPanel is a generic lightweight container.

Class Constructors:

1. JPanel(): Creates a new JPanel with a double buffer and a flow layout.

2. JPanel(boolean isDoubleBuffered): Creates a new JPanel with FlowLayout and

the specified buffering strategy.

3. JPanel(LayoutManager layout): Creates a new buffered JPanel with the specified

layout manager.

4. JPanel(LayoutManager layout, boolean isDoubleBuffered): Creates a new

JPanel with the specified layout manager and buffering strategy.

Class Methods:

1. AccessibleContext getAccessibleContext(): Gets the AccessibleContext

associated with this JPanel.

2. PanelUI getUI(): Returns the look and feel (L&F) object that renders this

component.
3. String getUIClassID(): Returns a string that specifies the name of the L&F class

which renders this component.

4. protected String paramString(): Returns a string representation of this JPanel.

5. void setUI(PanelUI ui): Sets the look and feel (L&F) object that renders this

component.

6. void updateUI(): Resets the UI property with a value from the current look and

feel.

JPanel Example:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class SwingContainerDemo {

private JFrame mainFrame;

private JLabel headerLabel;

private JLabel statusLabel;

private JPanel controlPanel;

private JLabel msglabel;

public SwingContainerDemo(){

prepareGUI();

public static void main(String[] args){

SwingContainerDemo swingContainerDemo = new SwingContainerDemo();

swingContainerDemo.showJPanelDemo();

private void prepareGUI(){


mainFrame = new JFrame("Java Swing Examples");

mainFrame.setSize(400,400);

mainFrame.setLayout(new GridLayout(3, 1));

mainFrame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

System.exit(0);

});

headerLabel = new JLabel("", JLabel.CENTER);

statusLabel = new JLabel("",JLabel.CENTER);

statusLabel.setSize(350,100);

msglabel = new JLabel("Welcome to CodersArts SWING blog",

JLabel.CENTER);

controlPanel = new JPanel();

controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);

mainFrame.add(controlPanel);

mainFrame.add(statusLabel);

mainFrame.setVisible(true);

private void showJPanelDemo(){

headerLabel.setText("Container in action: JPanel");

JPanel panel = new JPanel();

panel.setBackground(Color.magenta);

panel.setLayout(new FlowLayout());

panel.add(msglabel);
controlPanel.add(panel);

mainFrame.setVisible(true);

Output:

Introduction-JFrame:

The class JFrame is an extended version of java.awt.Frame that adds support for

the JFC/Swing component architecture.


Field

Following are the fields for java.awt.Component class −

 protected AccessibleContext accessibleContext −The accessible context

property.

 static int EXIT_ON_CLOSE − The exit application default window close operation.

 protected JRootPane rootPane − The JRootPane instance that manages the

contentPane and optional menuBar for this frame, as well as the glassPane.

 protected boolean rootPaneCheckingEnabled − If true then calls to add and

setLayout will be forwarded to the contentPane.

Class Constructors:

 JFrame(): Constructs a new frame that is initially invisible.

 JFrame(GraphicsConfiguration gc): Creates a Frame in the specified

GraphicsConfiguration of a screen device and a blank title.

 JFrame(String title): Creates a new, initially invisible Frame with the specified

title.

 JFrame(String title, GraphicsConfiguration gc): Creates a JFrame with the

specified title and the specified GraphicsConfiguration of a screen device.

Class Methods:

1. protected void addImpl(Component comp, Object constraints, int index):

Adds the specified child Component.


2. protected JRootPane createRootPane(): Called by the constructor methods to

create the default rootPane.

3. protected void frameInit(): Called by the constructors to init the JFrame properly.

4. AccessibleContext getAccessibleContext(): Gets the AccessibleContext

associated with this JFrame.

5. Container getContentPane(): Returns the contentPane object for this frame.

6. int getDefaultCloseOperation(): Returns the operation that occurs when the

user initiates a "close" on this frame.

7. Component getGlassPane(): Returns the glassPane object for this frame.

8. Graphics getGraphics(): Creates a graphics context for this component.

9. JMenuBar getJMenuBar(): Returns the menubar set on this frame.

10.JLayeredPane getLayeredPane(): Returns the layeredPane object for this frame.

11.JRootPane getRootPane(): Returns the rootPane object for this frame.

12.TransferHandler getTransferHandler(): Gets the transferHandler property.

13.static boolean isDefaultLookAndFeelDecorated(): Returns true if the newly

created JFrames have their Window decorations provided by the current look and

feel.

14.protected boolean isRootPaneCheckingEnabled(): Returns whether calls to

add and setLayout are forwarded to the contentPane.

15.protected String paramString(): Returns a string representation of this JFrame.

16.protected void processWindowEvent(WindowEvent e): Processes window

events occurring on this component.

17.void remove(Component comp): Removes the specified component from the

container.
18.void repaint(long time, int x, int y, int width, int height): Repaints the

specified rectangle of this component within time milliseconds.

19.void setContentPane(Container contentPane): Sets the contentPane property.

20.void setDefaultCloseOperation(int operation): Sets the operation that will

happen by default when the user initiates a "close" on this frame.

21.static void setDefaultLookAndFeelDecorated(boolean

defaultLookAndFeelDecorated): Provides a hint as to whether or not newly

created JFrames should have their Window decorations (such as borders, widgets to

close the window, title...) provided by the current look and feel.

22.void setGlassPane(Component glassPane): Sets the glassPane property.

23.void setIconImage(Image image): Sets the image to be displayed as the icon for

this window.

24.void setJMenuBar(JMenuBar menubar): Sets the menubar for this frame.

25.void setLayeredPane(JLayeredPane layeredPane): Sets the layeredPane

property.

26.void setLayout(LayoutManager manager): Sets the LayoutManager.

27.protected void setRootPane(JRootPane root): Sets the rootPane property.

28.protected void setRootPaneCheckingEnabled(boolean enabled): Sets

whether calls to add and setLayout are forwarded to the contentPane.

29.void setTransferHandler(TransferHandler newHandler): Sets the

transferHandler property, which is a mechanism to support the transfer of data into

this component.

30.void update(Graphics g): Just calls paint(g).

JFrame Example:

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

import javax.swing.*;

public class SwingContainerDemo {

private JFrame mainFrame;

private JLabel headerLabel;

private JLabel statusLabel;

private JPanel controlPanel;

private JLabel msglabel;

public SwingContainerDemo(){

prepareGUI();

public static void main(String[] args){

SwingContainerDemo swingContainerDemo = new SwingContainerDemo();

swingContainerDemo.showJFrameDemo();

private void prepareGUI(){

mainFrame = new JFrame("Java Swing Examples");

mainFrame.setSize(400,400);

mainFrame.setLayout(new GridLayout(3, 1));

mainFrame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

System.exit(0);

});

headerLabel = new JLabel("", JLabel.CENTER);


statusLabel = new JLabel("",JLabel.CENTER);

statusLabel.setSize(350,100);

msglabel = new JLabel("Welcome to CodersArts.", JLabel.CENTER);

controlPanel = new JPanel();

controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);

mainFrame.add(controlPanel);

mainFrame.add(statusLabel);

mainFrame.setVisible(true);

private void showJFrameDemo(){

headerLabel.setText("Container in action: JFrame");

final JFrame frame = new JFrame();

frame.setSize(400, 400);

frame.setLayout(new FlowLayout());

frame.add(msglabel);

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

frame.dispose();

});

JButton okButton = new JButton("Open a Frame");

okButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

statusLabel.setText("A Frame shown to the user.");


frame.setVisible(true);

});

controlPanel.add(okButton);

mainFrame.setVisible(true);

Output:

Introduction-JWindow

The class JWindow is a container that can be displayed but does not have the title

bar or window-management buttons.


Field

Following are the fields for java.awt.Component class −

 protected AccessibleContext accessibleContext − The accessible context

property.

 protected JRootPane rootPane − The JRootPane instance that manages the

contentPane and optional menuBar for this frame, as well as the glassPane.

 protected boolean rootPaneCheckingEnabled − If true then calls to add and

setLayout will be forwarded to the contentPane.

Class Constructors

 JWindow(): Creates a window with no specified owner.

 JWindow(Frame owner): Creates a window with the specified owner frame.

 JWindow(GraphicsConfiguration gc): Creates a window with the specified

GraphicsConfiguration of a screen device.

 JWindow(Window owner): Creates a window with the specified owner window.

 JWindow(Window owner, GraphicsConfiguration gc): Creates a window with

the specified owner window and GraphicsConfiguration of a screen device.

Class Methods

1. protected void addImpl(Component comp, Object constraints, int index):

Adds the specified child Component.

2. protected JRootPane createRootPane(): Called by the constructor methods to

create the default rootPane.

3. AccessibleContext getAccessibleContext(): Gets the AccessibleContext

associated with this JWindow.

4. Container getContentPane(): Returns the Container which is the contentPane for

this window.
5. Component getGlassPane(): Returns the glassPane Component for this window.

6. Graphics getGraphics(): Creates a graphics context for this component.

7. JLayeredPane getLayeredPane(): Returns the layeredPane object for this

window.

8. JRootPane getRootPane(): Returns the rootPane object for this window.

9. TransferHandler getTransferHandler(): Gets the transferHandler property.

10.protected boolean isRootPaneCheckingEnabled(): Returns whether calls to

add and setLayout are forwarded to the contentPane.

11.protected String paramString(): Returns a string representation of this JWindow.

12.void remove(Component comp): Removes the specified component from the

container.

13.void repaint(long time, int x, int y, int width, int height):Repaints the

specified rectangle of this component within time milliseconds.

14.void setContentPane(Container contentPane): Sets the contentPane property

for this window.

15.void setGlassPane(Component glassPane): Sets the glassPane property.

16.void setLayeredPane(JLayeredPane layeredPane): Sets the layeredPane

property.

17.void setLayout(LayoutManager manager): Sets the LayoutManager.

18.protected void setRootPane(JRootPane root): Sets the new rootPane object for

this window.

19.protected void setRootPaneCheckingEnabled(boolean enabled): Sets

whether calls to add and setLayout are forwarded to the contentPane.


20.void setTransferHandler(TransferHandler newHandler): Sets the

transferHandler property, which is a mechanism to support the transfer of data into

this component.

21.void update(Graphics g): Calls paint(g).

22.protected void windowInit(): Called by the constructors to init the JWindow

properly.

JWindow Example:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class SwingContainerDemo {

private JFrame mainFrame;

private JLabel headerLabel;

private JLabel statusLabel;

private JPanel controlPanel;

private JLabel msglabel;

public SwingContainerDemo(){

prepareGUI();

public static void main(String[] args){

SwingContainerDemo swingContainerDemo = new SwingContainerDemo();

swingContainerDemo.showJWindowDemo();
}

private void prepareGUI(){

mainFrame = new JFrame("Java Swing Examples");

mainFrame.setSize(400,400);

mainFrame.setLayout(new GridLayout(3, 1));

mainFrame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

System.exit(0);

});

headerLabel = new JLabel("", JLabel.CENTER);

statusLabel = new JLabel("",JLabel.CENTER);

statusLabel.setSize(350,100);

controlPanel = new JPanel();

controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);

mainFrame.add(controlPanel);

mainFrame.add(statusLabel);

mainFrame.setVisible(true);

private void showJWindowDemo(){

headerLabel.setText("Container in action: JWindow");

final MessageWindow window = new MessageWindow(

mainFrame, "Welcome to CodersArts.");


JButton okButton = new JButton("Open a Window");

okButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

window.setVisible(true);

statusLabel.setText("A Window shown to the user.");

});

controlPanel.add(okButton);

mainFrame.setVisible(true);

class MessageWindow extends JWindow{

private String message;

public MessageWindow(JFrame parent, String message) {

super(parent);

this.message = message;

setSize(400, 400);

setLocationRelativeTo(parent);

public void paint(Graphics g) {

super.paint(g);

g.drawRect(0,0,getSize().width - 1,getSize().height - 1);

g.drawString(message,50,150);

}
Output:

Types of Layout Manager in Java


In Java, graphical user interfaces (GUIs) play a vital role in creating interactive applications.
To design a visually appealing and organized interface, the choice of layout manager
becomes crucial. Layout managers define how components are arranged within a container,
such as a JFrame or JPanel. Java provides several layout managers to suit various design
needs. In this section, we will delve into the details of the different types of layout managers
available in Java, along with code examples and explanations.

1. FlowLayout
FlowLayout is a simple layout manager that arranges components in a row, left to right,
wrapping to the next line as needed. It is ideal for scenarios where components need to
maintain their natural sizes and maintain a flow-like structure.

FlowLayoutExample.java

1. import javax.swing.*;
2. import java.awt.*;
3. public class FlowLayoutExample {
4. public static void main(String[] args) {
5. JFrame frame = new JFrame("FlowLayout Example");
6. frame.setLayout(new FlowLayout());
7. frame.add(new JButton("Button 1"));
8. frame.add(new JButton("Button 2"));
9. frame.add(new JButton("Button 3"));
10. frame.pack();
11. frame.setVisible(true);
12. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13. }
14. }
Output:

2. BorderLayout
BorderLayout divides the container into five regions: NORTH, SOUTH, EAST, WEST, and
CENTER. Components can be added to these regions, and they will occupy the available
space accordingly. This layout manager is suitable for creating interfaces with distinct
sections, such as a title bar, content area, and status bar.

BorderLayoutExample.java

1. import javax.swing.*;
2. import java.awt.*;
3. public class BorderLayoutExample {
4. public static void main(String[] args) {
5. JFrame frame = new JFrame("BorderLayout Example");
6. frame.setLayout(new BorderLayout());
7. frame.add(new JButton("North"), BorderLayout.NORTH);
8. frame.add(new JButton("South"), BorderLayout.SOUTH);
9. frame.add(new JButton("East"), BorderLayout.EAST);
10. frame.add(new JButton("West"), BorderLayout.WEST);
11. frame.add(new JButton("Center"), BorderLayout.CENTER);
12. frame.pack();
13. frame.setVisible(true);
14. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15. }
16. }
Output:

3. GridLayout
GridLayout arranges components in a grid with a specified number of rows and columns.
Each cell in the grid can hold a component. This layout manager is ideal for creating a
uniform grid of components, such as a calculator or a game board.

GridLayoutExample.java

1. import javax.swing.*;
2. import java.awt.*;
3. public class GridLayoutExample {
4. public static void main(String[] args) {
5. JFrame frame = new JFrame("GridLayout Example");
6. frame.setLayout(new GridLayout(3, 3));
7. for (int i = 1; i <= 9; i++) {
8. frame.add(new JButton("Button " + i));
9. }
10. frame.pack();
11. frame.setVisible(true);
12. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13. }
14. }
Output:

Advertisement

4. CardLayout
CardLayout allows components to be stacked on top of each other, like a deck of cards.
Only one component is visible at a time, and you can switch between components using
methods like next() and previous(). This layout is useful for creating wizards or multi-step
processes.

CardLayoutExample.java

1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.ActionEvent;
4. import java.awt.event.ActionListener;
5. public class CardLayoutExample {
6. public static void main(String[] args) {
7. JFrame frame = new JFrame("CardLayout Example");
8. CardLayout cardLayout = new CardLayout();
9. JPanel cardPanel = new JPanel(cardLayout);
10. JButton button1 = new JButton("Card 1");
11. JButton button2 = new JButton("Card 2");
12. JButton button3 = new JButton("Card 3");
13. cardPanel.add(button1, "Card 1");
14. cardPanel.add(button2, "Card 2");
15. cardPanel.add(button3, "Card 3");
16. frame.add(cardPanel);
17. frame.pack();
18. frame.setVisible(true);
19. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. button1.addActionListener(e -> cardLayout.show(cardPanel, "Card 2"));
21. button2.addActionListener(e -> cardLayout.show(cardPanel, "Card 3"));
22. button3.addActionListener(e -> cardLayout.show(cardPanel, "Card 1"));
23. }
24. }
Output:

5. GroupLayout
GroupLayout is a versatile and complex layout manager that provides precise control over
the positioning and sizing of components. It arranges components in a hierarchical manner
using groups. GroupLayout is commonly used in GUI builders like the one in NetBeans IDE.

GroupLayoutExample.java

1. import javax.swing.*;
2. public class GroupLayoutExample {
3. public static void main(String[] args) {
4. JFrame frame = new JFrame("GroupLayout Example");
5. JPanel panel = new JPanel();
6. GroupLayout layout = new GroupLayout(panel);
7. panel.setLayout(layout);
8. JButton button1 = new JButton("Button 1");
9. JButton button2 = new JButton("Button 2");
10. layout.setHorizontalGroup(layout.createSequentialGroup()
11. .addComponent(button1)
12. .addComponent(button2));
13. layout.setVerticalGroup(layout.createParallelGroup()
14. .addComponent(button1)
15. .addComponent(button2));
16. frame.add(panel);
17. frame.pack();
18. frame.setVisible(true);
19. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. }
21. }
Output:
Advertisement

6. GridBagLayout
GridBagLayout is a powerful layout manager that allows you to create complex layouts by
specifying constraints for each component. It arranges components in a grid, but unlike
GridLayout, it allows components to span multiple rows and columns and have varying
sizes.

GridBagLayoutExample.java

1. import javax.swing.*;
2. import java.awt.*;
3. public class GridBagLayoutExample {
4. public static void main(String[] args) {
5. JFrame frame = new JFrame("GridBagLayout Example");
6. JPanel panel = new JPanel(new GridBagLayout());
7. GridBagConstraints constraints = new GridBagConstraints();
8. constraints.fill = GridBagConstraints.HORIZONTAL;
9. JButton button1 = new JButton("Button 1");
10. JButton button2 = new JButton("Button 2");
11. constraints.gridx = 0;
12. constraints.gridy = 0;
13. panel.add(button1, constraints);
14. constraints.gridx = 1;
15. panel.add(button2, constraints);
16. frame.add(panel);
17. frame.pack();
18. frame.setVisible(true);
19. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. }
21. }
Output:
Chapter 2

Event Handlers

Delegation Event Model in Java


The Delegation Event model is defined to handle events in GUI programming languages.
The GUI stands for Graphical User Interface, where a user graphically/visually interacts with
the system.

The GUI programming is inherently event-driven; whenever a user initiates an activity such
as a mouse activity, clicks, scrolling, etc., each is known as an event that is mapped to a
code to respond to functionality to the user. This is known as event handling.

In this section, we will discuss event processing and how to implement the delegation event
model in Java. We will also discuss the different components of an Event Model.

Event Processing in Java


Java support event processing since Java 1.0. It provides support for AWT ( Abstract
Window Toolkit), which is an API used to develop the Desktop application. In Java 1.0, the
AWT was based on inheritance. To catch and process GUI events for a program, it should
hold subclass GUI components and override action() or handleEvent() methods. The below
image demonstrates the event processing.

But, the modern approach for event processing is based on the Delegation Model. It defines
a standard and compatible mechanism to generate and process events. In this model, a
source generates an event and forwards it to one or more listeners. The listener waits until it
receives an event. Once it receives the event, it is processed by the listener and returns it.
The UI elements are able to delegate the processing of an event to a separate function.

The key advantage of the Delegation Event Model is that the application logic is completely
separated from the interface logic.

In this model, the listener must be connected with a source to receive the event
notifications. Thus, the events will only be received by the listeners who wish to receive
them. So, this approach is more convenient than the inheritance-based event model (in
Java 1.0).

In the older model, an event was propagated up the containment until a component was
handled. This needed components to receive events that were not processed, and it took
lots of time. The Delegation Event model overcame this issue.
Basically, an Event Model is based on the following three components:

o Events
o Events Sources
o Events Listeners

Events
The Events are the objects that define state change in a source. An event can be generated
as a reaction of a user while interacting with GUI elements. Some of the event generation
activities are moving the mouse pointer, clicking on a button, pressing the keyboard key,
selecting an item from the list, and so on. We can also consider many other user operations
as events.

The Events may also occur that may be not related to user interaction, such as a timer
expires, counter exceeded, system failures, or a task is completed, etc. We can define
events for any of the applied actions.

Event Sources
A source is an object that causes and generates an event. It generates an event when the
internal state of the object is changed. The sources are allowed to generate several
different types of events.

A source must register a listener to receive notifications for a specific event. Each event
contains its registration method. Below is an example:

1. public void addTypeListener (TypeListener e1)


From the above syntax, the Type is the name of the event, and e1 is a reference to the
event listener. For example, for a keyboard event listener, the method will be called
as addKeyListener(). For the mouse event listener, the method will be called
as addMouseMotionListener(). When an event is triggered using the respected source, all
the events will be notified to registered listeners and receive the event object. This process
is known as event multicasting. In few cases, the event notification will only be sent to
listeners that register to receive them.

Some listeners allow only one listener to register. Below is an example:

1. public void addTypeListener(TypeListener e2) throws java.util.TooManyListenersException


From the above syntax, the Type is the name of the event, and e2 is the event listener's
reference. When the specified event occurs, it will be notified to the registered listener. This
process is known as unicasting events.

A source should contain a method that unregisters a specific type of event from the listener
if not needed. Below is an example of the method that will remove the event from the
listener.
1. public void removeTypeListener(TypeListener e2?)
From the above syntax, the Type is an event name, and e2 is the reference of the listener.
For example, to remove the keyboard listener, the removeKeyListener() method will be
called.

The source provides the methods to add or remove listeners that generate the events. For
example, the Component class contains the methods to operate on the different types of
events, such as adding or removing them from the listener.

Event Listeners
An event listener is an object that is invoked when an event triggers. The listeners require
two things; first, it must be registered with a source; however, it can be registered with
several resources to receive notification about the events. Second, it must implement the
methods to receive and process the received notifications.

The methods that deal with the events are defined in a set of interfaces. These interfaces
can be found in the java.awt.event package.

For example, the MouseMotionListener interface provides two methods when the mouse
is dragged and moved. Any object can receive and process these events if it implements
the MouseMotionListener interface.

Types of Events
The events are categories into the following two categories:

The Foreground Events:

The foreground events are those events that require direct interaction of the user. These
types of events are generated as a result of user interaction with the GUI component. For
example, clicking on a button, mouse movement, pressing a keyboard key, selecting an
option from the list, etc.

The Background Events :

The Background events are those events that result from the interaction of the end-user.
For example, an Operating system interrupts system failure (Hardware or Software).

To handle these events, we need an event handling mechanism that provides control over
the events and responses.

The Delegation Model


The Delegation Model is available in Java since Java 1.1. it provides a new delegation-
based event model using AWT to resolve the event problems. It provides a convenient
mechanism to support complex Java programs.
Design Goals
The design goals of the event delegation model are as following:

o It is easy to learn and implement


o It supports a clean separation between application and GUI code.
o It provides robust event handling program code which is less error-prone (strong
compile-time checking)
o It is Flexible, can enable different types of application models for event flow and
propagation.
o It enables run-time discovery of both the component-generated events as well as
observable events.
o It provides support for the backward binary compatibility with the previous model.
Let's implement it with an example:

Java Program to Implement the Event Deligation Model


The below is a Java program to handle events implementing the event deligation model:

TestApp.java:

1. import java.awt.*;
2. import java.awt.event.*;
3.
4. public class TestApp {
5. public void search() {
6. // For searching
7. System.out.println("Searching...");
8. }
9. public void sort() {
10. // for sorting
11. System.out.println("Sorting....");
12. }
13.
14. static public void main(String args[]) {
15. TestApp app = new TestApp();
16. GUI gui = new GUI(app);
17. }
18. }
19.
20. class Command implements ActionListener {
21. static final int SEARCH = 0;
22. static final int SORT = 1;
23. int id;
24. TestApp app;
25.
26. public Command(int id, TestApp app) {
27. this.id = id;
28. this.app = app;
29. }
30.
31. public void actionPerformed(ActionEvent e) {
32. switch(id) {
33. case SEARCH:
34. app.search();
35. break;
36. case SORT:
37. app.sort();
38. break;
39. }
40. }
41. }
42.
43. class GUI {
44.
45. public GUI(TestApp app) {
46. Frame f = new Frame();
47. f.setLayout(new FlowLayout());
48.
49. Command searchCmd = new Command(Command.SEARCH, app);
50. Command sortCmd = new Command(Command.SORT, app);
51.
52. Button b;
53. f.add(b = new Button("Search"));
54. b.addActionListener(searchCmd);
55. f.add(b = new Button("Sort"));
56. b.addActionListener(sortCmd);
57.
58. List l;
59. f.add(l = new List());
60. l.add("Alphabetical");
61. l.add("Chronological");
62. l.addActionListener(sortCmd);
63. f.pack();
64.
65. f.show();
66. }
67. }
Output:
Event Classes in Java

Event Class Listener Interface Description

An event that indicates that a


component-defined action
ActionEvent ActionListener occurred like a button click or
selecting an item from the
menu-item list.

The adjustment event is emitted


AdjustmentEvent AdjustmentListener by an Adjustable object like
Scrollbar.

An event that indicates that a


component moved, the size
ComponentEvent ComponentListener
changed or changed its
visibility.

When a component is added to


a container (or) removed from
ContainerEvent ContainerListener
it, then this event is generated
by a container object.

These are focus-related events,


FocusEvent FocusListener which include focus, focusin,
focusout, and blur.

An event that indicates whether


ItemEvent ItemListener
an item was selected or not.

An event that occurs due to a


KeyEvent KeyListener sequence of keypresses on the
keyboard.

MouseEvent MouseListener & The events that occur due to


MouseMotionListener the user interaction with the
Event Class Listener Interface Description

mouse (Pointing Device).

An event that specifies that the


MouseWheelEvent MouseWheelListener mouse wheel was rotated in a
component.

An event that occurs when an


TextEvent TextListener
object’s text changes.

An event which indicates


WindowEvent WindowListener whether a window has changed
its status or not.

Event Adapters

Some listener interfaces contain more than one method. For example, the MouseListener interface contains
five methods: mousePressed, mouseReleased, mouseEntered, mouseExited, and mouseClicked.
Even if you care only about mouse clicks, if your class directly implements MouseListener, then you must
implement all five MouseListener methods. Methods for those events you do not care about can have
empty bodies. Here is an example:

//An example that implements a listener interface directly.


public class MyClass implements MouseListener {
...
someObject.addMouseListener(this);
...
/* Empty method definition. */
public void mousePressed(MouseEvent e) {
}

/* Empty method definition. */


public void mouseReleased(MouseEvent e) {
}

/* Empty method definition. */


public void mouseEntered(MouseEvent e) {
}

/* Empty method definition. */


public void mouseExited(MouseEvent e) {
}

public void mouseClicked(MouseEvent e) {


...//Event listener implementation goes here...
}
}

The resulting collection of empty method bodies can make code harder to read and maintain. To help you avoid
implementing empty method bodies, the API generally includes an adapter class for each listener interface with
more than one method. (The Listener API Table lists all the listeners and their adapters.) For example,
the MouseAdapter class implements the MouseListener interface. An adapter class implements empty
versions of all its interface's methods.

To use an adapter, you create a subclass of it and override only the methods of interest, rather than directly
implementing all methods of the listener interface. Here is an example of modifying the preceding code to
extend MouseAdapter. By extending MouseAdapter, it inherits empty definitions of all five of the methods
that MouseListener contains.

/*
* An example of extending an adapter class instead of
* directly implementing a listener interface.
*/
public class MyClass extends MouseAdapter {
...
someObject.addMouseListener(this);
...
public void mouseClicked(MouseEvent e) {
...//Event listener implementation goes here...
}
}

Inner Classes and Anonymous Inner Classes

What if you want to use an adapter class, but do not want your public class to inherit from an adapter class?
For example, suppose you write an applet, and you want your Applet subclass to contain some code to
handle mouse events. Since the Java language does not permit multiple inheritance, your class cannot extend
both the Applet and MouseAdapter classes. A solution is to define an inner class a class inside of
your Applet subclass that extends the MouseAdapter class.

Inner classes can also be useful for event listeners that implement one or more interfaces directly.

//An example of using an inner class.


public class MyClass extends Applet {
...
someObject.addMouseListener(new MyAdapter());
...
class MyAdapter extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
...//Event listener implementation goes here...
}
}
}

You can create an inner class without specifying a name this is known as an anonymous inner class. While it
might look strange at first glance, anonymous inner classes can make your code easier to read because the
class is defined where it is referenced. However, you need to weigh the convenience against possible
performance implications of increasing the number of classes.
Here is an example of using an anonymous inner class:

//An example of using an anonymous inner class.


public class MyClass extends Applet {
...
someObject.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
...//Event listener implementation goes here...
}
});
...
}
}

Inner classes work even if your event listener needs access to private instance variables from the enclosing
class. As long as you do not declare an inner class to be static, an inner class can refer to instance
variables and methods just as if its code is in the containing class. To make a local variable available to an
inner class, just save a copy of the variable as a final local variable.

To refer to the enclosing instance, you can use EnclosingClass.this.

The Mouse

A mouse generates six types of event messages that you can capture in your applets. These
events are listed below, along with their descriptions and the method that handles them:

 MOUSE_DOWN-This event, which is handled by the mouseDown() method, is caused


when the user presses the mouse button.
 MOUSE_UP-This event, which is handled by the mouseUp() method, is caused when
the user releases the left mouse button.
 MOUSE_MOVE-This event, which is handled by the mouseMove() method, occurs
when the user moves the mouse pointer on the screen.
 MOUSE_DRAG-This event, which is handled by the mouseDrag() method, is
generated when the user moves the mouse pointer while holding down the left mouse
button.
 MOUSE_ENTER-This event, which is handled by the mouseEnter() method, is sent
when the mouse pointer enters the area owned by an applet or component.
 MOUSE_EXIT-This event, which is handled by the mouseExit() method, occurs
when the mouse pointer leaves the area owned by an applet or a component.

In the sections that follow, you'll learn more about the most commonly used of these mouse
events.

Handling Mouse Clicks

Without a doubt, the most commonly used mouse event in Java is the MOUSE_DOWN event,
which is generated whenever the user clicks within an applet. It's the MOUSE_DOWN event, for
example, that lets Java know when an on-screen button component has been clicked. You don't
have to worry about clicks on on-screen buttons (usually), because they're handled by Java.
However, you can respond to MOUSE_DOWN events in your applets in order to accomplish other
input tasks.

Java provides a couple of methods by which you can respond to mouse events. The easiest way
to capture a MOUSE_DOWN event is to override the applet's mouseDown() method. Java
automatically calls mouseDown() whenever the MOUSE_DOWN event is generated, which
makes responding to this event easier than melting butter with a blowtorch.
The mouseDown() method's signature looks like this:

public boolean mouseDown(Event evt, int x, int y)

The arguments passed to the function are an Event object and the X,Y coordinates of the mouse
event. Although Java has already extracted the X,Y mouse coordinates for you, you can also get
them from the Event object by examining the values stored in the x and y data fields, as
described in Table 25.1. What you do with these coordinates depends, of course, on your applet.
In the next section, you'll see how to use the coordinates to display graphics on the screen.

Example: Using Mouse Clicks in an Applet

As I was describing the mouseDown() method in the previous section, I felt an example
coming on. And, sure enough, here it is. The applet in Listing 25.1 responds to mouse clicks by
printing the word "Click!" wherever the user clicks in the applet. It does this by storing the
coordinates of the mouse click in the applet's coordX and coordY data fields.
The paint() method then uses these coordinates to display the word. Figure 25.1 shows
MouseApplet running under Appletviewer.
Figure 25.1 : The MouseApplet applet responds to mouse clicks.

Listing 25.1 MouseApplet.java: Using Mouse Clicks in an Applet.

import java.awt.*;

import java.applet.*;

public class MouseApplet extends Applet

int coordX, coordY;

public void init()

coordX = -1;

coordY = -1;

Font font =

new Font("TimesRoman", Font.BOLD, 24);

setFont(font);

resize(400, 300);

public void paint(Graphics g)


{

if (coordX != -1)

g.drawString("Click!", coordX, coordY);

public boolean mouseDown(Event evt, int x, int y)

coordX = x;

coordY = y;

repaint();

return true;

Tell Java that the applet uses the classes in the awt package.
Tell Java that the applet uses the classes in the applet package.
Derive the MouseApplet class from Java's Applet class.
Declare the class's data fields.
Override the init() method.
Initialize the click coordinates.
Create and set the font for the applet.
Size the applet.
Override the paint() method.
If the user has selected a coordinate...
Draw the word Click! at the selected coordinate.
Override the mouseDown() method.
Save the mouse click's coordinates.
Force Java to repaint the applet.
Tell Java that the event was handled.
NOTE

When you run MouseApplet, you'll discover that the applet window gets
erased each time the paint() method is called. That's why only one
"Click!" ever appears in the window.

Handling Mouse Movement

Although mouse clicks are the most common type of mouse event to which your applet may
want to respond, tracking the mouse pointer's movement can also be useful. Drawing programs,
for example, enable you to draw shapes by tracking the movement of the mouse and displaying
the results on the screen.

Unlike mouse clicks, though, which are rare, only occurring when the user presses a mouse
button, MOUSE_MOVE events come flooding into your applet by the hundreds as the user moves
the mouse around the screen. Each one of these events can be handled in
the mouseMove() method, whose signature looks like this:

public boolean mouseMove(Event evt, int x, int y)

Yep. Except for its name, the mouseMove() method looks exactly like
the mouseDown() method, receiving as arguments an Event object and the X,Y coordinates
at which the event occurred.

Example: Responding to Mouse Movement in an Applet

Responding to mouse movement isn't something you have to do often in your applets. Still, it's a
handy tool to have on your belt. You might, for example, need to track mouse movement when
writing a game applet that uses the mouse as input. A more common use is in graphics programs
that enable you to draw on the screen. Listing 25.2 is just such an applet.

When you run MouseApplet2 with Appletviewer, you see a blank window. Click the mouse in
the window to choose a starting point and then move the mouse around the window. Wherever
the mouse pointer goes, it leaves a black line behind (Figure 25.2). Although this is a very simple
drawing program, it gives you some idea of how you might use a mouse to accomplish other
similar tasks.

Figure 25.2 : This applet draws by tracking the movement of the mouse.

Listing 25.2 MouseApplet2.java: An Applet That Tracks Mouse Movement.


import java.awt.*;

import java.applet.*;

public class MouseApplet2 extends Applet

Point startPoint;

Point points[];

int numPoints;

boolean drawing;

public void init()

startPoint = new Point(0, 0);

points = new Point[1000];

numPoints = 0;

drawing = false;

resize(400, 300);

public void paint(Graphics g)

int oldX = startPoint.x;

int oldY = startPoint.y;


for (int x=0; x<numPoints; ++x)

g.drawLine(oldX, oldY, points[x].x, points[x].y);

oldX = points[x].x;

oldY = points[x].y;

public boolean mouseDown(Event evt, int x, int y)

drawing = true;

startPoint.x = x;

startPoint.y = y;

return true;

public boolean mouseMove(Event evt, int x, int y)

if ((drawing) && (numPoints < 1000))

points[numPoints] = new Point(x, y);

++numPoints;

repaint();
}

return true;

Tell Java that the applet uses the classes in the awt package.
Tell Java that the applet uses the classes in the applet package.
Derive the MouseApplet2 class from Java's Applet class.
Declare the class's data fields.
Override the init() method.
Initialize the starting point.
Create an array for storing the coordinates of line segments.
Create and set the font for the applet.
Set point count to zero.
Set drawing flag off.
Size the applet.
Override the paint() method.
Initialize the drawing's starting point.
Cycle through each element in the points[] array.
Draw a line segment.
Save ending point as the starting point for the next line.
Override the mouseDown() method.
Set the flag in order to allow drawing to begin.
Save the mouse click's coordinates.
Tell Java that the event was handled.
Override the mouseMove() method.
if it's okay to add another line segment...
Create a new point and save the mouse's coordinates.
Increment the point counter.
Force Java to repaint the applet.
Tell Java that the event was handled.
The Keyboard

The keyboard has been around even longer than the mouse and has been the primary interface
between humans and their computers for decades. Given the keyboard's importance, obviously
there may be times when you'll want to handle the keyboard events at a lower level than you can
with something like a TextField control. Java responds to two basic key events, which are
represented by the KEY_PRESS and KEY_RELEASE constants. As you'll soon see, Java defines
methods that make it just as easy to respond to the keyboard as it is to respond to the mouse.

Responding to Key Presses

Whenever the user presses a key when an applet is active, Java sends the applet
a KEY_PRESS event. In your applet, you can respond to this event by overriding
the keyDown() method, whose signature looks like this:

public boolean keyDown(Event evt, int key)

As you can see, this method receives two arguments, which are an Event object and an integer
representing the key that was pressed. This integer is actually the ASCII representation of the
character represented by the key. In order to use this value in your programs, however, you must
first cast it to a char value, like this:

char c = (char)key;

Predefined Key Constants

Some of the keys on your keyboard issue commands rather than generate characters. These keys
include all the F keys, as well as keys like Shift, Ctrl, Page Up, Page Down, and so on. In order
to make these types of keys easier to handle in your applets, Java's Event class defines a set of
constants that represent these key's values. Table 25.2 lists these constants.

Table 25.2 Key Constants of the Event Class.

Constant Key

DOWN The down arrow key.

END The End key.

f1 The f1 key.
f2 The f2 key.

f3 The f3 key.

f4 The f4 key.

f5 The f5 key.

f6 The f6 key.

f7 The f7 key.

f8 The f8 key.

f9 The f9 key.

f10 The f10 key.

f11 The f11 key.

f12 The f12 key.

HOME The Home key.

LEFT The left arrow key.

PGDN The Page Down key.

PGUP The Page Up key.

RIGHT The right arrow key.

UP The up arrow key.

Key Modifiers

The Event class also defines a number of constants for modifier keys that the user might press
along with the basic key. These constants include ALT_MASK, SHIFT_MASK,
and CTRL_MASK, which represent the Alt, Shift, and Ctrl (or Control) keys on your keyboard.
The SHIFT_MASK and CTRL_MASK constants are used in the Event class's
methods shiftDown() and controlDown(), each which of returns a boolean value
indicating whether the modifier key is pressed. (There currently is no altDown() method.)
You can also examine the Event object's modifiers field to determine whether a particular
modifier key was pressed. For example, if you wanted to check for the Alt key, you might use a
line of Java code like this:

boolean altPressed = (evt.modifiers & Event.ALT_MASK) != 0;

By ANDing the mask with the value in the modifiers field, you end up with a non-zero value
if the Alt key was pressed and a 0 if it wasn't. You convert this result to a boolean value by
comparing the result with 0.

Example: Using Key Presses in an Applet

Although capturing key presses is a fairly simple process, there's nothing like an example applet
to put the theoretical stuff to the test. Listing 25.3 is an applet called KeyApplet that displays
whatever key the user presses. Figure 25.3 shows the applet running under Appletviewer.

Figure 25.3 : This applet displays the last character typed.

NOTE

If you run KeyApplet under a browser like Netscape Navigator, click on the
applet with your mouse before you start typing. This ensures that the
applet has the focus and will receive the key presses.

Listing 25.3 KeyApplet.java: An Applet That Captures Key Presses.

import java.awt.*;

import java.applet.*;

public class KeyApplet extends Applet

int keyPressed;

public void init()


{

keyPressed = -1;

Font font =

new Font("TimesRoman", Font.BOLD, 144);

setFont(font);

resize(200, 200);

public void paint(Graphics g)

String str = "";

if (keyPressed != -1)

str += (char)keyPressed;

g.drawString(str, 40, 150);

public boolean keyDown(Event evt, int key)

{
keyPressed = key;

repaint();

return true;

Tell Java that the applet uses the classes in the awt package.
Tell Java that the applet uses the classes in the applet package.
Derive the KeyApplet class from Java's Applet class.
Declare the class's data field.
Override the init() method.
Initialize keyPressed to indicate no valid key received yet.
Create and set the font for the applet.
Size the applet.
Override the paint() method.
Create the empty display string.
Draw the character on the screen.
Override the keyDown() method.
Save the key that was pressed.
Force Java to redraw the applet.
Tell Java that the event was handled.

You might also like