Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
CSIS 3701: Advanced Object-Oriented Programming
Java Visual Classes and Objects
Now that you have been introduced to the Java syntax for defining classes and creating
and using objects, you are now in a position to understand a lot more about Java’s builtin classes, as well as how applications are created in Java.
Java Visual Classes
One of the nicer things about Java is the large library of built-in classes for visual objects
such as buttons, textfields, etc. Like other classes, these contain constructors (often
overloaded) for creating these objects, and methods for manipulating their state (usually
involving what is displayed or what actions may be taken.
Some of the major classes that we will see right away are described below:
Class:
JButton
Main use:
Initiating events. In
the examples we have
seen, the
actionPerformed
method is invoked
when the button is
pressed.
JTextField Allowing the user to
enter text, and
displaying text for the
user.
JTextArea
Displays/enters text.
The difference
between this class and
JTextField is that
a textarea may be
Constructor:
JButton(String)
Takes a String as a
parameter, which is
displayed on the
button.
Useful methods:
setEnabled(boolean)
This enables/disables the button,
depending on whether the parameter
is true or false.
addActionListener(Object)
The object (the application, in this
case) “listens” for the event of the
button being pressed. We will cover
this in a lot more detail later.
JTextField(int) String getText()
Takes an integer as its Returns the String currently in the
parameter, uses it to
textfield.
create a textfield that
many characters wide. void setText(String)
Displays the String in the textfield.
void setEditable(boolean)
Determines whether the user can
enter new text in the textfield. If it is
true (the default) they can, and if it is
false, they cannot.
JTextField(int, String getText()
int)
void setText(String)
void setEditable(boolean)
The first parameter
sets the number of
void append(String)
rows, the second
multiple lines.
parameter sets the
width in characters.
Appends the string to the current
string displayed in the textarea,
rather than replacing it the way
setText does.
void setText(String)
Displays the String in the label.
JLabel
Displaying text (like
instructions, etc.)
JPanel
Added to surface of
application, used to
display other
components on itself.
JLabel(String)
Takes a String as a
parameter, which is
displayed on the label.
JPanel()
void add(Component)
Adds that component to its surface.
Importing Java Libraries
As with many languages, the actual Java language is rather small. Additional capabilities
(such as the above visual classes) are kept in libraries which the user may add when
needed.
In Java, libraries are included with the import statement. To import the classes necessary
to run most applications in Java 2, you need to import the libraries shown in the example
above:
import javax.swing.*;
import java.awt.event.*;
The syntax of these needs some explaining. Most libraries in Java are of the form
“java.library.class”. For example, to import the classes related to dates, you would do the
following:
import java.util.Date;
This is because the Date class is in the util library.
The quickest way to import all classes in a library is to use the standard wildcard
character * . To import all classes in the utility library, you would do:
import java.util.*;
Therefore, the statement java.awt.event.*; means “import all classes in the
awt.event library. This library contains the code necessary to do event handling in
Java.
The use of javax.swing.*; is kind of a special case. Java went through some major
changes between Java 1.1 and Java 2, including the way the above visual classes are
implemented, so its libraries are “java extension” libraries. These changes are often
referred to as swing. Most of the swing classes are in a separate library called
javax.swing in order to distinguish it from earlier versions of those classes. We
import this library to use the more modern versions of the visual components.
Java Application Classes
At this point, you now have the ability to take a fresh look at Java visual applications
themselves. While we will not explain everything about these applications yet, you
should be able to understand much of what you see.
Consider again the Hello class, particularly the lines of code in bold:
import javax.swing.*;
import java.awt.event.*;
public class Hello extends JFrame
implements ActionListener {
// line 1
private JButton go;
private JTextField greet;
// line 2
// line 3
public Hello() {
go = new JButton(“Press”);
greet = new JTextField(20);
go.addActionListener(this);
JPanel P = new JPanel();
getContentPane.add(P);
P.add(go);
P.add(greet);
setSize(400, 80);
setVisible(true);
}
//
//
//
//
//
line
line
line
line
line
4
5
6
7
8
//
//
//
//
line
line
line
line
9
10
11
12
// This code is run when the button is pressed
public void actionPerformed(ActionEvent e) {
greet.setText(“Welcome to Java Programming!”);
}
// line 13
// line 14
// This main program creates the Hello application
public static void main(String[] args) {
Hello h = new Hello();
// line 15
}
}
Like everything else in Java, visual applications are also classes. This means that they
will have constructors, methods, and state variables. They will also have other things we
will learn more about as we go on.
The first line, public class Hello means that Hello is a class, like the others we
have seen.
Lines 2 and 3,
private JButton go;
private JTextField greet;
define state variables for Hello objects. In this case, it means that each Hello
object contains a JButton called go and a JTextField called greet.
Note that almost all visual application classes contain the visual components they
display as state variables.
Line 4, public Hello() { defines the constructor for the Hello class.
Lines 5 and 6,
go = new JButton(“Press”);
greet = new JTextField(20);
construct the visual components go and greet.
If a visual application contains visual components as state variables, it usually
constructs them in its constructor.
Line 7, go.addActionListener(this) sends a message to the go object in order
to listen for the event of the button being pressed (we will explain exactly how this
works at a later time).
Line 8, JPanel P = new JPanel(); constructs a JPanel object to display the
components on.
Note that we have made P a local variable instead of a state variable. This is possible
since we never refer to P outside of the constructor. In general, it is more efficient to
use local variables rather than state variables where possible.
Lines 9 and 10,
P.add(go);
P.add(greet);
send the JPanel object P messages that cause it to add the visual components go
and greet.
Lines 11 and 12,
setSize(400, 80);
setVisible(true);
are necessary to make the application visible on the screen (note that this does not
happen automatically when the application is constructed!). This code does the
following:
o Sets the size of the object on the screen, in terms of its width and height (in
pixels) with the setSize method.
o Makes the object visible on the screen with the setVisible(true)
method.
Line 13, public void actionPerformed(ActionEvent e) { defines a method for
the Hello class called actionPerformed. This particular method is not called by
anything else we have seen – instead, it is automatically called when the button is
pressed (we will explain exactly how this works at a later time).
Note that most simple visual applications that use buttons will define the
actionPerformed method to handle button events.
Line 14, greet.setText(“Welcome to Java Programming!”); sends a message to
the greet object, telling it to display the string Welcome to Java Programming!.
Finally, most visual applications include a main method. This method is automatically
called when the java program is run – that is, when the command java Hello is run
from DOS, the main method of the Hello class is run.
This main method, like most you will see, does creates an instance of the object to be
displayed. This is done by invoking its constructor, as is done on line 15:
Hello h = new Hello();
We will examine in detail how the main method works in a later section.
A Further Example: A Roster Application
The Hello application class, while appearing fairly complex, is actually very simple in
many ways. In particular, it doesn’t really keep track of any states.
As a final example, we will define a class called Roster, which allows the user to input
the names in a class roster. This application will need to meet the following requirements:
The names must all be displayed as they are entered (we will use a TextArea for
this).
The user must be prevented from entering duplicate names. This means that the
application must keep a list of all names entered so far as a state variable.
The user must be prevented from entering more names than the maximum class size.
This means that the application must keep track of the number of names entered so
far and the maximum class size as a state variables. Once the maximum number of
names are entered, the ADD button will be disabled.
The actual class is given below:
// This application inputs and displays the roster
// of a course. It enforces and upper limit on the
// roster size, and prevents duplicate entries.
import javax.swing.*;
import java.awt.event. *;
public class Roster extends JFrame
implements ActionListener {
// State variables for visual components
private JButton addButton;
private JTextField nameField;
// name added to roster
private JTextArea namesArea;
// where all names displayed
// State variables for roster
private String[] names; // array of names in roster
private int howMany;
// how many names so far
private int max;
// maximum class size
// The constructor creates the visual components, and
// initalizes the class size to 0 and the max to 10.
public Roster() {
// Initialize state variables
howMany = 0;
max = 10;
// Construct the array, basing its size on the maximum
// number of names allowed.
names = new String[max];
// Construct the visual components
addButton = new JButton("ADD");
nameField = new JTextField(20);
// The number of rows in the textarea is based on the
// maximum number of names allowed.
namesArea = new JTextArea(max+1, 20);
// Listen for button events
addButton.addActionListener(this);
// Create panel and add components
JPanel P = new JPanel();
getContentPane().add(P);
P.add(addButton);
P.add(nameField);
P.add(namesArea);
setSize(320, 270);
show();
// set its size
// display it
}
// When the button is pressed, the name in the textfield is
// added to the roster and displayed in the textarea, unless
// the name is already on the roster
public void actionPerformed(ActionEvent e) {
// Get the name from the textfield
String name = nameField.getText();
// Compare it with the names
// the method without adding
for (int i = 0; i < howMany;
if (name.equals(names[i]))
already in the list, and exit
the name if it matches any.
i++)
return;
// Add the new name to the end of the list
names[howMany] = name;
// Increment the number of names in the list
howMany = howMany + 1;
// Append the new name to the textarea
namesArea.append(name + "\n");
// If the roster is full, disable the add button
if (howMany == max) addButton.setEnabled(false);
}
// Called when the application loaded.
public static void main(String[] args) {
RosterApp r = new RosterApp(); // construct the application
}
}
When run, this application will look something like this:
Finally, note that this is not necessarily the best way to solve the problem – we will show
a simpler and more modular solution in a later section.
Event Classes
Finally, note that like everything else in Java, events are represented as objects. For
example, consider the following line of code again:
public void actionPerformed(ActionEvent e) {
The variable e is an object in the ActionEvent class. This event object is created by
the button, and is passed to the actionEvent method when the button calls it. The
advantage of this is that it allows Java to pass information about the event to the
actionEvent handler.
This is particularly important if your application contains more than one button. In such a
case, you will need to access information about the event to find out which button has
been pressed.
This can be done with the getSource method in the ActionEvent class. This
method returns a reference to the button which was pressed.
We illustrate its use with a modification of the Hello class, one which contains two
buttons which print two different messages:
import javax.swing.*;
import java.awt.event.*;
// This class illustrates how event class methods can be used to find
// information about the nature of an event -- in this case, which of
// two buttons has been pressed.
public class Hello2 extends JFrame
implements ActionListener {
// Two buttons
private JButton first, second;
private JTextField greet;
public Hello2() {
first = new JButton("Introduction");
second = new JButton("Current message");
greet = new JTextField(30);
// listen for events on both buttons
first.addActionListener(this);
second.addActionListener(this);
JPanel P = new JPanel();
getContentPane().add(P);
P.add(first);
P.add(second);
P.add(greet);
setSize(400, 160);
setVIsible(true);
}
// This code is run when _either_ button is pressed
public void actionPerformed(ActionEvent e) {
// Send a message to the event object e to find which button
// was pressed. This returns a reference to the button which
// was pressed.
if (e.getSource() == first)
greet.setText("Welcome to Java Programming!");
else
greet.setText("Hope you're enjoying Java Programming!");
}
// This main program creates the Hello application
public static void main(String[] args) {
Hello2 h = new Hello2();
}
}
Some other examples of the kind of information passed this way in Java include:
o When the mouse is moved, that causes a MouseEvent. This class includes
getX and getY methods which allow you to find the current position of the
mouse.
o When items are selected from lists, that causes an ItemEvent. This class
includes getSelectedItem methods which allow you to find the which item
was selected.
Copyright © 2000 by Dr. John R. Sullins