java
java
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)
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
8. Select OK.
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.
An exception that occurs at the runtime or at the time of execution is known as an unchecked exception.
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.
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:
If you say
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
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:
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.
The following table highlights the major differences between Multiprocessing and Multithreading −
Multiprocessing can be
classified into symmetric No such classification
Categories
and asymmetric present for multithreading.
multiprocessing.
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.
Unit – 5
Now you can generate the summary of any article of your choice.
Got it
Execution Time is more than Swing. Execution Time is less than AWT.
// Main class
class GFG {
Example 2: Write a program to create three buttons with caption OK, SUBMIT, CANCEL.
Java
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);
}
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.
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.
Platform-
Architecture Platform-Dependent
Independent
By default, it is not
Thread Safety Thread-safe by default
thread-safe
and it provides the capability to add a component to itself. Following are certain
Sub classes of Container are called as Container. For example, JPanel, JFrame and
JWindow.
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
Introduction-JPanel:
Class Constructors:
1. JPanel(): Creates a new JPanel with a double buffer and a flow layout.
layout manager.
Class Methods:
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
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 SwingContainerDemo(){
prepareGUI();
swingContainerDemo.showJPanelDemo();
mainFrame.setSize(400,400);
mainFrame.addWindowListener(new WindowAdapter() {
System.exit(0);
});
statusLabel.setSize(350,100);
JLabel.CENTER);
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
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
property.
static int EXIT_ON_CLOSE − The exit application default window close operation.
contentPane and optional menuBar for this frame, as well as the glassPane.
Class Constructors:
JFrame(String title): Creates a new, initially invisible Frame with the specified
title.
Class Methods:
3. protected void frameInit(): Called by the constructors to init the JFrame properly.
created JFrames have their Window decorations provided by the current look and
feel.
container.
18.void repaint(long time, int x, int y, int width, int height): Repaints the
created JFrames should have their Window decorations (such as borders, widgets to
close the window, title...) provided by the current look and feel.
23.void setIconImage(Image image): Sets the image to be displayed as the icon for
this window.
property.
this component.
JFrame Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public SwingContainerDemo(){
prepareGUI();
swingContainerDemo.showJFrameDemo();
mainFrame.setSize(400,400);
mainFrame.addWindowListener(new WindowAdapter() {
System.exit(0);
});
statusLabel.setSize(350,100);
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
frame.setSize(400, 400);
frame.setLayout(new FlowLayout());
frame.add(msglabel);
frame.addWindowListener(new WindowAdapter() {
frame.dispose();
});
okButton.addActionListener(new ActionListener() {
});
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
property.
contentPane and optional menuBar for this frame, as well as the glassPane.
Class Constructors
Class Methods
this window.
5. Component getGlassPane(): Returns the glassPane Component for this window.
window.
container.
13.void repaint(long time, int x, int y, int width, int height):Repaints the
property.
18.protected void setRootPane(JRootPane root): Sets the new rootPane object for
this window.
this component.
properly.
JWindow Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public SwingContainerDemo(){
prepareGUI();
swingContainerDemo.showJWindowDemo();
}
mainFrame.setSize(400,400);
mainFrame.addWindowListener(new WindowAdapter() {
System.exit(0);
});
statusLabel.setSize(350,100);
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
okButton.addActionListener(new ActionListener() {
window.setVisible(true);
});
controlPanel.add(okButton);
mainFrame.setVisible(true);
super(parent);
this.message = message;
setSize(400, 400);
setLocationRelativeTo(parent);
super.paint(g);
g.drawString(message,50,150);
}
Output:
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
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.
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:
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 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 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.
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 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:
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...
}
}
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.
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:
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.
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:
In the sections that follow, you'll learn more about the most commonly used of these mouse
events.
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:
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.
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.
import java.awt.*;
import java.applet.*;
coordX = -1;
coordY = -1;
Font font =
setFont(font);
resize(400, 300);
if (coordX != -1)
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.
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:
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.
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.
import java.applet.*;
Point startPoint;
Point points[];
int numPoints;
boolean drawing;
numPoints = 0;
drawing = false;
resize(400, 300);
oldX = points[x].x;
oldY = points[x].y;
drawing = true;
startPoint.x = x;
startPoint.y = y;
return true;
++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.
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:
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;
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.
Constant 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.
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:
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.
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.
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.
import java.awt.*;
import java.applet.*;
int keyPressed;
keyPressed = -1;
Font font =
setFont(font);
resize(200, 200);
if (keyPressed != -1)
str += (char)keyPressed;
{
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.