Fig. 2.8: Addition - Java An Addition Program
Fig. 2.8: Addition - Java An Addition Program
import javax.swing.JOptionPane;
import javax.swing.JApplet;
import java.awt.Graphics;
The class JOptionPane (javax.swing) allows you to display a dialog box containing info.
• showMessageDialog(), showInputDialog()
Graphics object:
• drawString(), drawLine(), drawOval(), drawRect()
/ Fig. 3.12: AdditionApplet.java Adding two floating-point numbers
import java.awt.Graphics;
import javax.swing.*;
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
JOptionPane.showMessageDialog(
null, outputTextArea, "Compound Interest",
JOptionPane.INFORMATION_MESSAGE );
JTextArea (javax.swing) is a GUI component that is capable of displaying many lines of text.
The arguments determine the number of rows and columns as well as the size on the screen.
append(), setText()
Fig. 5.6: An interesting feature of class JOptionPane is that the message it displays with
showMessageDialog can be a String or a GUI component such as a JtextArea.
import java.awt.Graphics;
import javax.swing.*;
input = JOptionPane.showInputDialog(
"Enter 1 to draw lines\n" +
"Enter 2 to draw rectangles\n" +
"Enter 3 to draw ovals\n" );
} // end switch
} // end for
} // end paint()
} // end class SwitchTest
/ Fig. 5.19: LogicalOperators.java Demonstrating the logical operators
import javax.swing.*;
output += "Logical AND (&&)" + "\nfalse && false: " + ( false && false ) + "\nfalse && true: "
+ ( false && true ) + "\ntrue && false: " + ( true && false ) + "\ntrue && true: " + ( true && true );
outputArea.setText( output );
System.exit( 0 );
}
}
Fig 5-19: Class JScrollPane (javax.swing) provides a GUI component with scrolling
functionality. It is initialized with the GUI component for which it will provide scrolling.
JScrollPane scroller = new JSP( outputArea);
/ Fig. 6.3: SquareInt.java A programmer-defined square method
import java.awt.Container;
import javax.swing.*;
int result;
outputArea.setText( output );
}
Fig 6.3: Displays a GUI component on an applet. The on-screen display area for a Japplet has a
content pane to which the GUI components must be attached so they can be displayed at
execution time.
Container c = getContentPane();
c.add(outputArea);
Method getContentPane() returns a reference to the applet’s content pane. The add() method
places the JTextArea object on the applet so it can be displayed when executed.
Fig 6.9: Container and FlowLayout are imported from java.awt. The java.awt.event contains
many data types that enable a program to process a user’s interactions with a program
(ActionListener, ActionEvent). JApplet, JLabel, JLextField and JButton are imported from
javax.swing.
A JLabel contains a string of chars to display on the screen. It normally indicates the purpose of
another gui element on the screen.
JTextFields are used to get a single line of info from the user at the keyboard or to display info
on the screen.
• setEditable(): with argument false indicates that it is not editable (gray background).
Method init() creates the gui components and attaches them to the user interface.
This method defines the layout manager for the applet’s user interface. Layout managers are
provided to arrange components on a Container for presentation purposes. They determine the
position and size of every component attached.
FlowLayout is the most basic manager. GUI components are placed from left to right in the
order in which they are attached to the Container with the method add().
Each Container can have only one layout manager at a time. Separate Containers in the same
program can have different managers.
The interface ActionListener specifies that the class must define the method:
This method is used to process a user’s interaction with the JButton. When the user presses the
button, this method will be called automatically in response to the user interaction (event). This
process is called event handling. The handler is the actionPerfomed() method.
roll.addActionListener( this );
The above method registers the applet (this) as the listener for events from the JButton roll.
When a GUI event occurs in a program, Java creates an object containing info about the event
that occurred and automatically calls an appropriate event handling method.
Before any event can be processed, each GUI component must know which object in the
program defines the event handling method that will be called when the event occurs.
To respond to an action event, we must define a class that implements ActionListener (that
requires that the class also define method actionPerformed() ) and we must register the event
handler.
actionPerformed() receives one argument – an ActionEvent – which contains info about the
action that has occurred.
// Fig. 6.9: Craps.java Craps
final int WON = 0, LOST = 1, CONTINUE = 2; // const varis for status of game
public void actionPerformed( ActionEvent e ) { // call method play when button is pressed
play();
}
public void play() { // process one roll of the dice
if ( firstRoll ) { // first roll of the dice
sumOfDice = rollDice();
switch ( sumOfDice ) {
case 7: case 11: // win on first roll
gameStatus = WON;
point.setText( "" ); // clear point text field
break;
case 2: case 3: case 12: // lose on first roll
gameStatus = LOST;
point.setText( "" ); // clear point text field
break;
default: // remember point
gameStatus = CONTINUE;
myPoint = sumOfDice;
point.setText( Integer.toString( myPoint ) );
firstRoll = false;
break;
}
}
else {
sumOfDice = rollDice();
if ( sumOfDice == myPoint ) // win by making point
gameStatus = WON;
else
if ( sumOfDice == 7 ) // lose by rolling 7
gameStatus = LOST;
}
if ( gameStatus == CONTINUE )
showStatus( "Roll again." );
else {
if ( gameStatus == WON )
showStatus( "Player wins. " + "Click Roll Dice to play again." );
else
showStatus( "Player loses. " + "Click Roll Dice to play again." );
firstRoll = true;
}
}
Fig 6-13: In this example, the user presses the Enter key while typing in the JTextField num to
generate the action event.
Automatically, a message is sent to the applet indication that the user interacted with one of the
program’s GUI components.
The message e.getActionCommand(), when executed inside the handler, returns the string the
user typed in the JTextField before pressing the Enter key.
// Fig. 8.5: TimeTest.java Demonstrating the Time3 class set and get methods
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.deitel.jhtp3.ch08.Time3;
private Time3 t;
private JLabel hourLabel, minuteLabel, secondLabel;
private JTextField hourField, minuteField, secondField, display;
private JButton tickButton;
Container c = getContentPane();
updateDisplay();
}
public void actionPerformed( ActionEvent e )
{
if ( e.getSource() == tickButton )
tick();
else if ( e.getSource() == hourField ) {
t.setHour( Integer.parseInt( e.getActionCommand() ) );
hourField.setText( "" );
}
else if ( e.getSource() == minuteField ) {
t.setMinute( Integer.parseInt( e.getActionCommand() ) );
minuteField.setText( "" );
}
else if ( e.getSource() == secondField ) {
t.setSecond( Integer.parseInt( e.getActionCommand() ) );
secondField.setText( "" );
}
updateDisplay();
}
if ( t.getSecond() == 0 ) {
t.setMinute( ( t.getMinute() + 1 ) % 60 );
if ( t.getMinute() == 0 )
t.setHour( ( t.getHour() + 1 ) % 24 );
}
}
}
Fig 8-5: Several GUI components that are being handled with the same method. The handler
uses e.getSource() to determine which component generated the event. The ActionEvent
parameter that is supplied to the handler contains a refernce to the source.
/ Fig. 9.12: Time.java Time class definition
// Fig. 9.12: TimeTestWindow.java Demonstrating the Time class set and get methods
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
t = new Time();
Container c = getContentPane();
displayTime();
}
}
}
Fig 9-12: TimeTestWindow extends JFrame (javax.swing) rather than JApplet. This class
provides the basic attributes and behavior of a window – a title bar and buttons to minimize,
maximize and close the window.
The init() method of the applet has been replaced by a constructor so that the GUI components
are created as the application begins executing.
Defines one instance of an inner class and assigns it to handler. This reference is passed to each
of the calls to addActionListener() to register it as the event handler.
The inner class is defined as private because its only used in this class definition. An inner class
object has a special relationship with the outer class object creates it. The inner class object is
allowed to access directly all the instance variables and methods of the outer class object.
// Fig. 9.13: TimeTestWindow.java Demonstrating the Time class set and get methods
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
private Time t;
private JLabel hourLabel, minuteLabel, secondLabel;
private JTextField hourField, minuteField, secondField, display;
public TimeTestWindow()
{
super( "Inner Class Demonstration" );
t = new Time();
Container c = getContentPane();
hourField.addActionListener(
new ActionListener() { // anonymous inner class
public void actionPerformed( ActionEvent e )
{
t.setHour(
Integer.parseInt( e.getActionCommand() ) );
hourField.setText( "" );
displayTime();
}
}
);
c.add( hourLabel );
c.add( hourField );
minuteField.addActionListener(
new ActionListener() { // anonymous inner class
public void actionPerformed( ActionEvent e )
{
t.setMinute(
Integer.parseInt( e.getActionCommand() ) );
minuteField.setText( "" );
displayTime();
}
}
);
c.add( minuteLabel );
c.add( minuteField );
secondField.addActionListener(
new ActionListener() { // anonymous inner class
public void actionPerformed( ActionEvent e )
{
t.setSecond(
Integer.parseInt( e.getActionCommand() ) );
secondField.setText( "" );
displayTime();
}
}
);
c.add( secondLabel );
c.add( secondField );
window.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
Each of the JTextFields that generate events have a similar anonymous inner class to handle
events.
hourField.addActionListener(
new ActionListener() { // a i c
public void actionPerformed(ActionEvent e) {
t.setHour( Integer.parseInt( e.getActionCommand() ) );
hourField.setText( " " );
displayTime();
}
}
);
The body of the class (between { } ) defines one method to be called when the user presses Enter
while typing in hourField.
Windows generate a variety of events. This example deals with the event generated when the
user clicks the window’s close box – a window closing event.
window.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit( 0 );
}
}
);
The method addWindowListener() registers the window event listener. The argument must be a
reference to an object the is a WindowListener (java.awt.event).
However, there are seven different methods that must be defined in every class that implements
the interface, and we only need one for the window closing event.
For event handling interfaces with more than one method, Java provides a corresponding class
(adapter class) that already implements all the methods in the interface for you. All you need to
do is extend the adapter class and override the methods you require.
The syntax WindowAdapter( ) begins the definition of an anonymous inner class that extends
class WindowAdapter. This is similar to beginning a class definition with:
1. Compiling a class that contains inner classes results in a separate .class file for every class.
Inner classes have the file name OuterClassName$InnerClassName.class
2. Inner classes with class names can be defined public, private, package access, or protected
and are subject to the same usage restrictions as other members of a class.
4. The outer class is responsible for creating objs of its inner classes. To create an obj of
another class’s inner class, first create obj of the outer class and assign it to a refernce (lets
call it ref). Then use a statement of the following form to create an inner class obj:
5. An inner class can be declared static. These do not require an obj of its outer class to be
defined. A static IC does not have access to the outer class’s non-static members.
Swing Overview
The Swing components allow the programmer to specify a different look and feel for each
platform, or a uniform one across all, or even change the look and feel while running.
Hierarchy: java.lang.Object
java.awt.Component
ava.awt.Container
javax.swing.JComponent
Fig 12-4: Example using labels with and without icons and different alignments. Many swing
components can display images by specifying an Icon as an argument to their constructor or by
using a method that is normally called setIcon().
label3.setHorizontalPosition(SwingConstants.CENTER)
// Fig. 12.4: LabelTest.java. Demonstrating the JLabel class.
public LabelTest()
{
super( "Testing JLabel" );
Container c = getContentPane();
c.setLayout( new FlowLayout() );
label1 = new JLabel( "Label with text" ); // JLabel constructor with a string argument
label1.setToolTipText( "This is label1" );
c.add( label1 );
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}
// Fig. 12.7: TextFieldTest.java Demonstrating the JTextField class.
public TextFieldTest() {
super( "Testing JTextField and JPasswordField" );
Container c = getContentPane();
c.setLayout( new FlowLayout() );
text2 = new JTextField( "Enter text here" ); // construct textfield with default text
c.add( text2 );
text3 = new JTextField( "Uneditable text field", 20 ); // construct textfield with default text and 20
text3.setEditable( false ); // visible elements and no event handler
c.add( text3 );
password = new JPasswordField( "Hidden text" ); // construct textfield with default text
c.add( password );
Fig 12-10: The icon on the button changes as the mouse moves in and out of the button’s area
on the screen. A JButton can display Icons and can also have a rollover Icon – one that is
displayed when the mouse is positioned over the button.
fancyButton.setRolloverIcon(bug2);
Buttons generate ActionEvents that can be processed by any ActionListener object with the
method actionPerformed(). The inner class handler displays a message dialog box containing the
label for the button that was pressed by the user. The ActionEvent method
e.getActionCommand() returns the label.
Fig 12-11: Changes the style of the text field by selecting check buttons. One JCheckButton
applies a bold style and the other italic. When the user clicks a JCheckButton an ItemEvent is
generated that can be handled by an ItemListener.
The ItemListener obj must define the method itemStateChanged( ). This example uses an inner
class as handler that determines the button checked with getSource() and the state of the button
as follows:
if ( e.getStateChange() == ItemEvent.SELECTED )
valBold = Font.BOLD;
else
valBold = Font.PLAIN;
Fig 12-12: Uses JRadioButtons that permit only a single font style to be selected. The
constructor of the radio button specifies the label and the initial state.
The above object is the “glue” that binds the four radio buttons together to form a logical
relationship that allows only one of the buttons to be selected at a time. Class
RadioButtonHandler implements the ItemListener interface so it can handle events generated by
the radio buttons.
// Fig. 12.10: ButtonTest.java Creating JButtons.
public ButtonTest()
{
super( "Testing Buttons" );
Container c = getContentPane();
c.setLayout( new FlowLayout() );
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
public CheckBoxTest() {
super( "JCheckBox Test" );
Container c = getContentPane();
c.setLayout(new FlowLayout());
if ( e.getSource() == italic )
if ( e.getStateChange() == ItemEvent.SELECTED )
valItalic = Font.ITALIC;
else
valItalic = Font.PLAIN;
public RadioButtonTest() {
super( "RadioButton Test" );
Container c = getContentPane();
c.setLayout( new FlowLayout() );
plain = new JRadioButton( "Plain", true ); c.add( plain ); // Create radio buttons
bold = new JRadioButton( "Bold", false); c.add( bold );
italic = new JRadioButton( "Italic", false ); c.add( italic );
boldItalic = new JRadioButton( "Bold/Italic", false ); c.add( boldItalic );
public ComboBoxTest() {
super( "Testing JComboBox" );
Container c = getContentPane();
c.setLayout( new FlowLayout() );
c.add( images );
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}
Fig 12-13: Uses a JComboBox to provide a list of four image file names, that when selected its
displayed as an Icon on a JLabel.
Creates a combo box obj using the string in array names as the elements in the list. A numeric
index keeps track of the ordering of items.
images.setMaximumRowCount(3);
Sets the maximum number of elements that are displayed when the user clicks the combo box. If
there are more items than the max, the combo box automatically provides a scrollbar.
The handler obtains the index of the item selected with method getSelectedIndex().
Fig 12-17: Each mouse event results in a string displayed in a JLabel at the bottom of the
window. Uses the default layout manager, BorderLayout, that divides the content pane’s area
into five regions - north, south, east, west and center.
Attaches the JLabel statusBar to the south region which extends across the entire bottom of the
content pane.
The application window is registered as the listener for its own mouse events. When the mouse
enters or exits the application area the corresponding event handlers display a message in
statusBar indicating the event.
When any of the other five events occur, they display a message describing the event and the
coordinates where the event occurred. With the getX() and getY() MouseEvent methods.
// Fig. 12.17: MouseTracker.java Demonstrating mouse events.
public MouseTracker() {
super( "Demonstrating Mouse Events" );
statusBar = new JLabel();
getContentPane().add( statusBar, BorderLayout.SOUTH );
public Painter()
{
super( "A simple paint program" );
getContentPane().add(
new Label( "Drag the mouse to draw" ),
BorderLayout.SOUTH );
addMouseMotionListener(
new MouseMotionAdapter() {
public void mouseDragged( MouseEvent e )
{
xValue = e.getX();
yValue = e.getY();
repaint();
}
}
);
setSize( 300, 150 );
show();
}
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}
Fig 12-19: Uses the mouseDragged event handler to create a simple drawing program. The
user can draw pictures with by dragging the mouse on the background of the window.
Since method mouseMoved is not used, the MouseMotionListener is defined as a subclass of
MouseMotionAdapter and then we override mouseDragged.
The handler captures the x and y coordinates of the mouse-dragged event and stores them in
instance variables xValue and yValue, then calls repaint() to initiate drawing of the next oval on
the background.
As you drag the mouse all ovals remain on the window. This is due to a special feature of Swing
GUI components called double buffering in which all drawing actually occurs in an image stored
in memory, then the entire image is displayed on the window. This helps present smooth
graphics display in a GUI.
// Fig. 12.20: MouseDetails.java Demonstrating mouse clicks and distinguishing between mouse buttons.
public MouseDetails() {
super( "Mouse clicks and buttons" );
addMouseListener( new MouseClickHandler() );
setSize( 350, 150 );
show();
}
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
Key events are generated when keys are pressed and released. To implement the KeyListener
interface a class must provide definitions for methods keyPressed, keyReleased and keyTyped.
Each of these receive a KeyEvent as its argument.
keyTyped: called in response to pressing any key that is not an action key (arrow key, Home,
End, Page Up, Page Down, function key, Num Lock, Print Screen, Scroll Lock, Caps Lock
and Pause).
keyReleased: called when the key is released after any keyPressed or keyTyped event.
Fig 12-22: The constructor registers the application to handle its own key events with method
addKeyListener( ). This method is defined in class Component, so every subclass can notify
KeyListeners of key events for that Component.
A JTextArea is added to display the output. It occupies the entire window. When a single
Component is added to a BorderLayout, it occupies the entire Container by default.
Methods keyPressed and keyReleased use KeyEvent method getKeyCode to get the virtual key
code of the key that was pressed. The value returned is passed to KeyEvent method getKeyText
which returns a string containing the name of the key that was pressed.
Method keyTyped uses KeyEvent method getKeyChar to get the Unicode value of the character
typed.
All three handlers call method setLines2and3( ) passing it the event object. This method uses
the KeyEvent method isActionKey to determine if the key was an action key.
InputEvent mehtod getModifiers is called to determine if any modifier keys (Shift, Alt and Ctrl)
where pressed. The result is passed to KeyEvent method getKeyModifiersText, which produces
a string containing the names of the pressed modifier keys.
// Fig. 12.22: KeyDemo.java Demonstrating keystroke events.
public KeyDemo() {
super( "Demonstrating Keystroke Events" );
getContentPane().add( textArea );
The layout managers provide basic layout capabilities that are easier to use than determining the
exact position and size of every GUI component.
FlowLayout: the most basic layout manager. Components are placed on a container from left to
right in the order in which they are added. When the edge is reached, components aer continued
on the next line. Allows components to be left-aligned, centered (default) and right-aligned.
Fig 12-24: Creates three buttons and adds them to the application using a FlowLayout. The user
can click the Left, Right or Center buttons to change the alignment.
layout.layoutContainer( c );
Uses the LayoutManager’s interface method to specify that the content pane should be
rearranged based on the adjusted layout.
BorderLayout: Arranges components into five regions. Up to five components can be added
directly - one for each region. If all five regions are occupied, the entire container’s space is
covered. If a region is not occupied (except center), the other regions expand to fill the
remaining space.
Fig 12-25: Places five buttons on a BorderLayout. When a button is clicked, it is hidden and the
window is adjusted.
The arguments specify the number of pixels between components. The horizontal gap and the
vertical gap (default is 0).
The handler uses setVisible to hide the button. The LayoutManager method layoutContainer is
used to recalculate the layout of the content pane.
// Fig. 12.24: FlowLayoutDemo.java Demonstrating FlowLayout alignments.
public FlowLayoutDemo() {
super( "FlowLayout Demo" );
layout = new FlowLayout();
c = getContentPane();
c.setLayout( layout );
public BorderLayoutDemo() {
super( "BorderLayout Demo" );
Container c = getContentPane();
c.setLayout( layout );
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e ) {
System.exit( 0 );
}
}
);
}
}
GridLayout: divides the container into a grid so that components can be placed in rows and
columns. Every component has the same width and height. They are added starting at the top
left cell of the grid and proceeding left to right.
Fig 12-26: Adds six button to a GridLayout. Defines two GridLayout objects which are
switched when a button is pressed.
The object grid1 is a layout with 2 rows, 3 columns and 5 pixels at the gaps. Object grid2
specifies 3 rows, 2 columns and no gap space.
Every call to actionPerformed toggles the layout between grid2 and grid1. The method
validate() illustrates another way to re-layout a container for which the layout has changed. It
re-computes the container’s layout based on the current layout manager and the current set of
displayed components.
Panels: Complex GUIs require that each component be placed in an exact location. They often
consist of multiple panels with each panel’s components arranged in a specific layout. A JPanel
is a subclass of JComponent that inherits from class Container. Thus, JPanels may have
components, including other panels, added to them.
Fig 12-27: A JPanel is created with a GridLayout. Five buttons are added to the panel which is
then added to the south region of a BorderLayout.
The buttons are added directly to the JPanel - class JPanel does not have a content pane like an
applet or a JFrame.
/ Fig. 12.26: GridLayoutDemo.java Demonstrating GridLayout.
public GridLayoutDemo() {
super( "GridLayout Demo" );
c = getContentPane();
c.setLayout( grid1 );
toggle = !toggle;
c.validate();
}
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e ) {
System.exit( 0 );
}
}
);
}
}
// Fig. 12.27: PanelDemo.java Using a JPanel to help lay out components.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public PanelDemo()
{
super( "Panel Demo" );
Container c = getContentPane();
buttonPanel = new JPanel();
buttons = new JButton[ 5 ];
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}