0% found this document useful (0 votes)
10 views

Java CIS 260 Notes Part 3

Java CIS 260 Notes part 3

Uploaded by

fastalan392
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Java CIS 260 Notes Part 3

Java CIS 260 Notes part 3

Uploaded by

fastalan392
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 37

1

Chapter Interlude: More on Strings

More on Strings

Strings are objects which mean they are reference variables this
means that

 = Comparison actually tests the reference address of each string


variable, not the string itself. To compare strings use the equal
method of the string which returns a Boolean value (true or false)

String sX = “fred”;
String sY = “sam”;
if ( sX.equal(sY) )
{
System.out.println(“yes, they are equal”);
}
else
{
System.out.println(“no, they are not”);
}

 When assigning a string value using the = operator and a string, a


new destination string is being created. This makes assignment work
a lot like call by value (primitive) variables

// Pass String
// Show how strings are different when used with =
public class test3
{

public static void main( String args[] )


{
String sX = "Hi";
String sY = "bye";

System.out.println("sX=" + sX + " sY=" + sY );

modifyString( sX, sY ); // array passed by reference


System.out.println("");

System.out.println("sX=" + sX + " sY=" + sY);

System.out.println("");
2
System.exit( 0 );
} // end main

// modify strings
public static void modifyString( String sOne, String sTwo )
{
String sBubba = "end";
sOne = "Red";
sTwo = sBubba;
}

} // end class PassArray


3
Chapter 10: Graphics, JFrame, Fonts, Drawing

Graphics

Graphics involves everything that goes into display of images on a


computer screen. The screen consists of X by Y “array” of picture
elements called pixels. Each pixel can assume one color and in
combination form the images we see

 Resolution refers to the number of columns (x value_ and rows (Y


value) of pixels. Typically in a 4:3 aspect ration such as 640 by
480, 800 by 600, etc. The higher the resolution the less pixilated
(jagged) an image looks. But also the more memory size, bandwidth
and computation power that is required

 Depth refers to the maximum number of colors that can be


represented on screen. Usually a power of two. 8 bit depth gives
256 colors, 16 gives 64k colors, etc. The more depth the more colors
(and theoretically the better looking the image). But, as above more
also the more memory, processor and bandwidth are required

 Color each pixel has a color which is determined by three values.


Typically either Red, Green and Blue (RGB) which represent the
intensity of the primary computer colors. Or, Hue, Saturation and
Value (HSV) which is simply a different system used to achieve the
same ends

 API application programming interface. A library that abstracts


manipulating these pixels and color values to a much higher level.
For Java this means providing such things as color selection,
buttons, text entry boxes and primitive drawing functions (line,
circle, etc)
4
 Graphics Context (gc) a handle for the machine specific portions of
the display and routines that are implemented to drive them.

The drawable screen in Java is composed of an X by Y grid with 0,0


being in the upper left. X-axis is horizontal and Y-axis being
vertical. All coordinates are relative to the upper left corner the
window java is drawing in which means title bar and such overly part
of the window. To find this information out use Insets from
java.awt. Four fields Insets:top, Insets:bottom, Insets:left and
Insets:right are provided. They provide the offsets that is used up
by the decorations on the window

Color Control we have several built in constants for predefined color


values, as well as a color classes that allow us to read R,G or B
color values and set a color as well. When you set a color, that
will be the color used to draw almost all objects until changed (some
pattern fills / textures, etcetera break this rule). Note that swing
includes a color chooser which allows you to pick a color graphically
and returns the selection as a Color object

 Constructors Color(int,int,int) and Color(float, float, float)


where the floats are bound to the range 0 to 1.

 Reading color values with int getRed(), int getBlue() and int
getGreen() or all at once with Color getColor().

 Setting Color Values with void setColor( Color )

JFrame

JFrame is an application’s (non-applet’s) way of handling a GUI. A


JFrame is simply a graphical container that you can place and
manipulate GUI objects in. You can also add other methods as well.
The steps to create a JFrame are the following
5
 Create a class that extends JFrame. This will be our GUI window
object

constructor method should configure initial window settings

paint method describes what the user sees

 Create a class with a main method. This is our driver program that
will launch our window class by code like

Fonts application = new Fonts();


application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

Code Example)

// Fig. 12.5: ShowColors.java


// Demonstrating Colors.
import java.awt.*;
import javax.swing.*;

public class ShowColors extends JFrame


{
// constructor sets window's title bar string and dimensions
public ShowColors()
{
super( "Using colors" );

setSize( 400, 130 );


setVisible( true );
}

// draw rectangles and Strings in different colors


public void paint( Graphics g )
{
// call superclass's paint method
super.paint( g );

// set new drawing color using integers


g.setColor( new Color( 255, 0, 0 ) );
g.fillRect( 25, 25, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 40 );

// set new drawing color using floats


6
g.setColor( new Color( 0.0f, 1.0f, 0.0f ) );
g.fillRect( 25, 50, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 65 );

// set new drawing color using static Color objects


g.setColor( Color.BLUE );
g.fillRect( 25, 75, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 90 );

// display individual RGB values


Color color = Color.MAGENTA;
g.setColor( color );
g.fillRect( 25, 100, 100, 20 );
g.drawString( "RGB values: " + color.getRed() + ", " +
color.getGreen() + ", " + color.getBlue(), 130, 115 );

} // end method paint

// execute application
public static void main( String args[] )
{
ShowColors application = new ShowColors();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

} // end class ShowColors

Fonts

Fonts can be examined and set via a variety of methods and fields
that work with the Font class. Please note that not all fonts are
available for all users, but Java does requires that (Serif,
Monospaced and SanSerif are available). Font sizes are specified in
points where one point is 1/72 of an inch

 Constructor Font( String Name, int style, int sizeInPts )

 Reading Font Properties uses String getName(), String getFamiy(),


int getStyle(), int getSize(). There are also some Boolean tests for
the styles that you can apply to fonts including, Boolean isPlain(),
Boolean isBold() and Boolean isItalic(). And, you can also retreie a
font object via Font getFont()
7

 Reading Font Metrics provides “techie” info about a font with int
getAscent(), int getDescent(), getLeading(), int getHeight() as well
as FontMetrics getFontMetrics() and FontMetrics getFontMetrics( Font
) where FontMetrics is a class with the methods described for this
entry

 Setting a Font can be done via void setFont( Font )

Code Example)

// Using fonts.
import java.awt.*;
import javax.swing.*;

public class Fonts extends JFrame


{

// set window's title bar and dimensions


public Fonts()
{
super( "Using fonts" );

setSize( 420, 125 );


setVisible( true );
}

// display Strings in different fonts and colors


public void paint( Graphics g )
{
// call superclass's paint method
super.paint( g );

// set font to Serif (Times), bold, 12pt and draw a string


g.setFont( new Font( "Serif", Font.BOLD, 12 ) );
g.drawString( "Serif 12 point bold.", 20, 50 );

// set font to Monospaced (Courier), italic, 24pt and draw a


string
g.setFont( new Font( "Monospaced", Font.ITALIC, 24 ) );
g.drawString( "Monospaced 24 point italic.", 20, 70 );

// set font to SansSerif (Helvetica), plain, 14pt and draw a


string
g.setFont( new Font( "SansSerif", Font.PLAIN, 14 ) );
8
g.drawString( "SansSerif 14 point plain.", 20, 90 );

// set font to Serif (Times), bold/italic, 18pt and draw a


string
g.setColor( Color.RED );
g.setFont( new Font( "Serif", Font.BOLD + Font.ITALIC, 18 ) );
g.drawString( g.getFont().getName() + " " +
g.getFont().getSize() +
" point bold italic.", 20, 110 );

} // end method paint

// execute application
public static void main( String args[] )
{
Fonts application = new Fonts();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

} // end class Fonts

Code Example)

// Fig. 12.12: Metrics.java


// FontMetrics and Graphics methods useful for obtaining font
metrics.
import java.awt.*;
import javax.swing.*;

public class Metrics extends JFrame


{

// set window's title bar String and dimensions


public Metrics()
{
super( "Demonstrating FontMetrics" );

setSize( 510, 210 );


setVisible( true );
}

// display font metrics


public void paint( Graphics g )
{
super.paint( g ); // call superclass's paint method
9

g.setFont( new Font( "SansSerif", Font.BOLD, 12 ) );


FontMetrics metrics = g.getFontMetrics();
g.drawString( "Current font: " + g.getFont(), 10, 40 );
g.drawString( "Ascent: " + metrics.getAscent(), 10, 55 );
g.drawString( "Descent: " + metrics.getDescent(), 10, 70 );
g.drawString( "Height: " + metrics.getHeight(), 10, 85 );
g.drawString( "Leading: " + metrics.getLeading(), 10, 100 );

Font font = new Font( "Serif", Font.ITALIC, 14 );


metrics = g.getFontMetrics( font );
g.setFont( font );
g.drawString( "Current font: " + font, 10, 130 );
g.drawString( "Ascent: " + metrics.getAscent(), 10, 145 );
g.drawString( "Descent: " + metrics.getDescent(), 10, 160 );
g.drawString( "Height: " + metrics.getHeight(), 10, 175 );
g.drawString( "Leading: " + metrics.getLeading(), 10, 190 );

} // end method paint

// execute application
public static void main( String args[] )
{
Metrics application = new Metrics();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

} // end class Metrics

Drawing

Drawing Methods for Lines, Rectangles and Ovals

 Draw lines with void drawLine( intX1, intY1, int intX2, intY2)

 Draw rectangles with void drawRect( intX, intY, intWidth, intheight


). You can also draw a filled (foreground color) rectangle with void
fillRect( intX, intY, intWidth, intheight ), or one that uses the
background color void clearRect( intX, intY, intWidth, intheight )
10
 Draw rounded rectangles with void drawRoundRect( intX, intY,
intWidth, intheight ) and void fillRoundRect( intX, intY, intWidth,
intheight )

 Draw a “3D” rectangles with void draw3DRect( intX, intY, intWidth,


intheight, boolPressed ) and void fill3DRect( intX, intY, intWidth,
intheight, bolPressed ). Here a boolPressed of true equals a raised
appearance and false appears pressed

 Draw ovals with void drawOval( intX, intY, intWidth, intheight ).


You can also draw a filled (foreground color) oval with void
fillOval( intX, intY, intWidth, intheight )

Code Example)

// Fig. 12.14: LinesRectsOvals.java


// Drawing lines, rectangles and ovals.
import java.awt.*;
import javax.swing.*;

public class LinesRectsOvals extends JFrame {

// set window's title bar String and dimensions


public LinesRectsOvals()
{
super( "Drawing lines, rectangles and ovals" );

setSize( 400, 165 );


setVisible( true );
}

// display various lines, rectangles and ovals


public void paint( Graphics g )
{
super.paint( g ); // call superclass's paint method

g.setColor( Color.RED );
g.drawLine( 5, 30, 350, 30 );

g.setColor( Color.BLUE );
g.drawRect( 5, 40, 90, 55 );
g.fillRect( 100, 40, 90, 55 );
11
g.setColor( Color.CYAN );
g.fillRoundRect( 195, 40, 90, 55, 50, 50 );
g.drawRoundRect( 290, 40, 90, 55, 20, 20 );

g.setColor( Color.YELLOW );
g.draw3DRect( 5, 100, 90, 55, true );
g.fill3DRect( 100, 100, 90, 55, false );

g.setColor( Color.MAGENTA );
g.drawOval( 195, 100, 90, 55 );
g.fillOval( 290, 100, 90, 55 );

} // end method paint

// execute application
public static void main( String args[] )
{
LinesRectsOvals application = new LinesRectsOvals();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

} // end class LinesRectsOvals

Methods for drawing arcs involve specifying a 2d rectangle to draw


the arc within, as well as a start and stop degree used to specify
the “circumference and location” of the arc in question. 0 is dead
east and 360 is just above dead east. The methods are void
drawArc(intX, intY, intWidth, intheight, intStartAngle,
intStopAngle ) and fillArc(intX, intY, intWidth, intheight,
intStartAngle, intStopAngle )

Code Example)

// Fig. 12.19: DrawArcs.java


// Drawing arcs.
import java.awt.*;
import javax.swing.*;

public class DrawArcs extends JFrame


{

// set window's title bar String and dimensions


public DrawArcs()
{
12
super( "Drawing Arcs" );

setSize( 300, 170 );


setVisible( true );
}

// draw rectangles and arcs


public void paint( Graphics g )
{
super.paint( g ); // call superclass's paint method

// start at 0 and sweep 360 degrees


g.setColor( Color.YELLOW );
g.drawRect( 15, 35, 80, 80 );
g.setColor( Color.BLACK );
g.drawArc( 15, 35, 80, 80, 0, 360 );

// start at 0 and sweep 110 degrees


g.setColor( Color.YELLOW );
g.drawRect( 100, 35, 80, 80 );
g.setColor( Color.BLACK );
g.drawArc( 100, 35, 80, 80, 0, 110 );

// start at 0 and sweep -270 degrees


g.setColor( Color.YELLOW );
g.drawRect( 185, 35, 80, 80 );
g.setColor( Color.BLACK );
g.drawArc( 185, 35, 80, 80, 0, -270 );

// start at 0 and sweep 360 degrees


g.fillArc( 15, 120, 80, 40, 0, 360 );

// start at 270 and sweep -90 degrees


g.fillArc( 100, 120, 80, 40, 270, -90 );

// start at 0 and sweep -270 degrees


g.fillArc( 185, 120, 80, 40, 0, -270 );

} // end method paint

// execute application
public static void main( String args[] )
{
DrawArcs application = new DrawArcs();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class DrawArcs
13

Drawing Polygons can be accomplished via methods and/or a Polygon


class.

 Methods for drawing polygons include void drawPolygon( intX[],


intY[], intPoints ) and fillPolygon( intX[], intY[], intPoints ) were
intPoints specifies how many points to draw of those passed. It will
close the polygon if the last point does not match the first. Or,
drawPolyLine(intX[], intY[], intPoints ) which will not close the
resulting figure

The polygon class itself supports a constructors Polygon() and


Polygon(intX[], intY[], intPoints ). It also offers the ability to
add points later via the polygon method addPoints( intX, intY ).
There is a graphics deawPolygon( Polygon ) Method as well

Code Example)

// Fig. 12.21: DrawPolygons.java


// Drawing polygons.
import java.awt.*;
import javax.swing.*;

public class DrawPolygons extends JFrame


{

// set window's title bar String and dimensions


public DrawPolygons()
{
super( "Drawing Polygons" );

setSize( 275, 230 );


setVisible( true );
}

// draw polygons and polylines


public void paint( Graphics g )
{
super.paint( g ); // call superclass's paint method

int xValues[] = { 20, 40, 50, 30, 20, 15 };


int yValues[] = { 50, 50, 60, 80, 80, 60 };
Polygon polygon1 = new Polygon( xValues, yValues, 6 );
14

g.drawPolygon( polygon1 );

int xValues2[] = { 70, 90, 100, 80, 70, 65, 60 };


int yValues2[] = { 100, 100, 110, 110, 130, 110, 90 };

g.drawPolyline( xValues2, yValues2, 7 );

int xValues3[] = { 120, 140, 150, 190 };


int yValues3[] = { 40, 70, 80, 60 };

g.fillPolygon( xValues3, yValues3, 4 );

Polygon polygon2 = new Polygon();


polygon2.addPoint( 165, 135 );
polygon2.addPoint( 175, 150 );
polygon2.addPoint( 270, 200 );
polygon2.addPoint( 200, 220 );
polygon2.addPoint( 130, 180 );

g.fillPolygon( polygon2 );

} // end method paint

// execute application
public static void main( String args[] )
{
DrawPolygons application = new DrawPolygons();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

} // end class DrawPolygons

Chapter 11: Events, Inner/Anonymous Classes, JTextField, JButton


15

Events

Event Handling means dealing with GUI input as if it where


“asynchronous” and “multithreaded.” Asynchronous because we are
unsure when events may occur in relation to our program flow
(when/how events are detected is hidden from the programmer).
Multithreaded, because any number of events can be triggered at one
moment.

The three areas of events we are concerned with are

 Event Source which object triggered (is affected by) the event

 Event Object is an encapsulated “message” describing the event and


containing a reference to the object which caused the event

 Event Listener is the code which waits to receive the event object.
It must both be registered with the event source as well as have code
that will handle the event in question. This is the portion we
write to handle events

The events listeners we can use are provided as interfaces that you
can implement in your code. Generally, this is done by the use of
inner classes. The event interface system is as follows

EventListener
ActionListener
AdjustmentListener
ComponentListener
ContainerListener
FocusListener
ItemListener
KeyListener
MouseListener
MouseMotionListener
TextListner
WindowListener
16

How Events are set up

 Define a class and ALL the methods in the class to handle a


particular listener interface. In our case, Write a TextField
handler class that extends ActionListener and defines
actionPerformed()

 Instantiate this class for each class of GUI widget / event


listener you wish. Ex) TextFieldHandler handler = new
TextFieldHandler(); Which is fine for all text fields we my use
since the code will be the same. If this is not the case, we will
need different classes

 Register the instance of your class with each object . Ex)


MyText.addActionListener( handle );

Inner/Anonymous Classes

Inner Classes and Anonymous Inner Classes are two ways we can use to
create our event classes. Both involve creating a class inside a
class (our GUI class)

 Inner Classes follow rules similar to other classes except for a


few points. First, that the class is declared and defined inside
anther class. Second, that all encapsulated methods and class wide
variables are available to the inner class as well as any local
variables of the method the inner class is instantiated in

 Anonymous Inner Classes are similar to inner classes, but are


declared, defined and instantiated in one use fashion. I.e. you can
only instantiate them once

JTextField

JTextField and JPasswordField hold a single line of text that is


enterable by the user. The JPasswordField varient echos * to the
17
text field. Use inteli-sense to learn about the methods and field
variables available

Code Example)

// Fig. 13.7: TextFieldTest.java


// Demonstrating the JTextField class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TextFieldTest extends JFrame


{
private JTextField textField1, textField2, textField3;
private JPasswordField passwordField;

// set up GUI
public TextFieldTest()
{
super( "Testing JTextField and JPasswordField" );

Container container = getContentPane();


container.setLayout( new FlowLayout() );

// construct textfield with default sizing


textField1 = new JTextField( 10 );
container.add( textField1 );

// construct textfield with default text


textField2 = new JTextField( "Enter text here" );
container.add( textField2 );

// construct textfield with default text,


// 20 visible elements and no event handler
textField3 = new JTextField( "Uneditable text field", 20 );
textField3.setEditable( false );
container.add( textField3 );

// construct passwordfield with default text


passwordField = new JPasswordField( "Hidden text" );
container.add( passwordField );

// register event handlers


TextFieldHandler handler = new TextFieldHandler();
textField1.addActionListener( handler );
textField2.addActionListener( handler );
18
textField3.addActionListener( handler );
passwordField.addActionListener( handler );

setSize( 325, 100 );


setVisible( true );

} // end constructor TextFieldTest

public static void main( String args[] )


{
TextFieldTest application = new TextFieldTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

// private inner class for event handling


private class TextFieldHandler implements ActionListener
{
// process textfield events
public void actionPerformed( ActionEvent event )
{
String string = "";

// user pressed Enter in JTextField textField1


if ( event.getSource() == textField1 )
{
string = "textField1: " + event.getActionCommand();
}
// user pressed Enter in JTextField textField2
else if ( event.getSource() == textField2 )
{
string = "textField2: " + event.getActionCommand();
}
// user pressed Enter in JTextField textField3
else if ( event.getSource() == textField3 )
{
string = "textField3: " + event.getActionCommand();
}
// user pressed Enter in JTextField passwordField
else if ( event.getSource() == passwordField )
{
string = "passwordField: " +
new String( passwordField.getPassword() );
}

JOptionPane.showMessageDialog( null, string );

} // end method actionPerformed


19
} // end private inner class TextFieldHandler

} // end class TextFieldTest

JButton

JButton is a typical button. Use inteli-sense to learn about the


methods and field variables available

Code Example)

// Fig. 13.10: ButtonTest.java


// Creating JButtons.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonTest extends JFrame


{
private JButton plainButton, fancyButton;

// set up GUI
public ButtonTest()
{
super( "Testing Buttons" );

// get content pane and set its layout


Container container = getContentPane();
container.setLayout( new FlowLayout() );

// create buttons
plainButton = new JButton( "Plain Button" );
container.add( plainButton );

Icon bug1 = new ImageIcon( "bug1.gif" );


Icon bug2 = new ImageIcon( "bug2.gif" );
fancyButton = new JButton( "Fancy Button", bug1 );
fancyButton.setRolloverIcon( bug2 );
container.add( fancyButton );

// create an instance of inner class ButtonHandler


// to use for button event handling
ButtonHandler handler = new ButtonHandler();
fancyButton.addActionListener( handler );
20
plainButton.addActionListener( handler );

setSize( 275, 100 );


setVisible( true );

} // end ButtonTest constructor

public static void main( String args[] )


{
ButtonTest application = new ButtonTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

// inner class for button event handling


private class ButtonHandler implements ActionListener {

// handle button event


public void actionPerformed( ActionEvent event )
{
JOptionPane.showMessageDialog( ButtonTest.this,
"You pressed: " + event.getActionCommand() );
}

} // end private inner class ButtonHandler

} // end class ButtonTest

Combining Both

// Creating test5
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class test5 extends JFrame


{
private JButton plainButton, fancyButton;
private JTextField txtTest;

// set up GUI
public test5()
{
super( "Testing Buttons" );

// get content pane and set its layout


Container container = getContentPane();
21
container.setLayout( new FlowLayout() );

// create buttons
plainButton = new JButton( "Plain Button" );
container.add( plainButton );

Icon bug1 = new ImageIcon( "bug1.gif" );


Icon bug2 = new ImageIcon( "bug2.gif" );
fancyButton = new JButton( "Fancy Button", bug1 );
fancyButton.setRolloverIcon( bug2 );
container.add( fancyButton );

txtTest = new JTextField( "", 20);


container.add( txtTest );

// create an instance of inner class ButtonHandler


// to use for button event handling
ButtonHandler handler = new ButtonHandler();
fancyButton.addActionListener( handler );
plainButton.addActionListener( handler );

setSize( 275, 100 );


setVisible( true );

} // end ButtonTest constructor

public static void main( String args[] )


{
test5 application = new test5();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

// inner class for button event handling


private class ButtonHandler implements ActionListener {

// handle button event


public void actionPerformed( ActionEvent event )
{
JOptionPane.showMessageDialog( test5.this,
"You pressed: " + event.getActionCommand() + " and the
text is " + txtTest.getText() );
}

} // end private inner class ButtonHandler


} // end class ButtonTest
Chapter 12: Flow, Border, Grid, Panel Layout Managers
22

Flow Layout Manager

Layout Mangers allow you to more easily position components in


container. There are several varieties of layout mangers which
control how components will appear on the screen, we will examine,
Flow, Border, Grid. Note that if you set a layout manager to null
(rather than set a layout manager), you must absolutely position
every object you wish to place.

Widgets you can set layout with include

 Content Pane defaults to border layout if you do not set a layout

 JPanel defaults to flow layout if you do not set a layout

FlowLayout places components left to right and then over onto the
“next line” when more space is needed. FlowLayout supports alignment
and components may be ordered using a second integer argument to the
add method. The Constructors are supported as follows with alignment
argument supporting FlowLayout.LEADING (left -> right),
FlowLayout.CENTER, or FlowLayout.TRAILING (right -> left). And, the
gap arguments specify the number of pixels to put between components,
default is 5

 public FlowLayout()

 public FlowLayout(int alignment)

 public FlowLayout(int alignment, int horizontalGap, int


verticalGap)

Code Example)

// Fig. 13.24: FlowLayoutDemo.java


23
// Demonstrating FlowLayout alignments.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FlowLayoutDemo extends JFrame


{
private JButton leftButton, centerButton, rightButton;
private Container container;
private FlowLayout layout;

// set up GUI and register button listeners


public FlowLayoutDemo()
{
super( "FlowLayout Demo" );

layout = new FlowLayout();

// get content pane and set its layout


container = getContentPane();
container.setLayout( layout );

// set up leftButton and register listener


leftButton = new JButton( "Left" );
container.add( leftButton );
leftButton.addActionListener(

new ActionListener()
{ // anonymous inner class

// process leftButton event


public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.LEFT );

// realign attached components


layout.layoutContainer( container );
}

} // end anonymous inner class

); // end call to addActionListener

// set up centerButton and register listener


centerButton = new JButton( "Center" );
container.add( centerButton );
centerButton.addActionListener(
24
new ActionListener()
{ // anonymous inner class

// process centerButton event


public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.CENTER );

// realign attached components


layout.layoutContainer( container );
}
}
);

// set up rightButton and register listener


rightButton = new JButton( "Right" );
container.add( rightButton );
rightButton.addActionListener(

new ActionListener()
{ // anonymous inner class

// process rightButton event


public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.RIGHT );

// realign attached components


layout.layoutContainer( container );
}
}
);

setSize( 300, 75 );
setVisible( true );

} // end constructor FlowLayoutDemo

public static void main( String args[] )


{
FlowLayoutDemo application = new FlowLayoutDemo();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

} // end class FlowLayoutDemo


Border Layout Manager
25
Border Layout allows selection of five areas for placement of your
widgets. The old style naming scheme of NORTH, EAST, SOUTH, WEST and
CENTER or the new style of PAGE_START, LINE_START, PAGE_END, LINE_END
and CENTER. You are limited to 4 widgets per space, but you may
nest containers inn a space.
Excluding any area, but CENTER, will result in the other areas
expanding to fill available real estate. The Constructors are
supported as follows with gap arguments specify the number of pixels
to put between components, default is 5

 public BorderLayout()

 public BorderLayout(int horizontalGap, int verticalGap)

Code Example)

// Fig. 13.25: BorderLayoutDemo.java


// Demonstrating BorderLayout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BorderLayoutDemo extends JFrame implements


ActionListener
{
private JButton buttons[];
private final String names[] = { "Hide North", "Hide South",
"Hide East", "Hide West", "Hide Center" };
private BorderLayout layout;

// set up GUI and event handling


public BorderLayoutDemo()
{
super( "BorderLayout Demo" );

layout = new BorderLayout( 5, 5 ); // 5 pixel gaps

// get content pane and set its layout


Container container = getContentPane();
container.setLayout( layout );

// instantiate button objects


buttons = new JButton[ names.length ];
26
for ( int count = 0; count < names.length; count++ )
{
buttons[ count ] = new JButton( names[ count ] );
buttons[ count ].addActionListener( this );
}

// place buttons in BorderLayout; order not important


container.add( buttons[ 0 ], BorderLayout.NORTH );
container.add( buttons[ 1 ], BorderLayout.SOUTH );
container.add( buttons[ 2 ], BorderLayout.EAST );
container.add( buttons[ 3 ], BorderLayout.WEST );
container.add( buttons[ 4 ], BorderLayout.CENTER );

setSize( 300, 200 );


setVisible( true );

} // end constructor BorderLayoutDemo

// handle button events


public void actionPerformed( ActionEvent event )
{
for ( int count = 0; count < buttons.length; count++ )

if ( event.getSource() == buttons[ count ] )


buttons[ count ].setVisible( false );
else
buttons[ count ].setVisible( true );

// re-layout the content pane


layout.layoutContainer( getContentPane() );
}

public static void main( String args[] )


{
BorderLayoutDemo application = new BorderLayoutDemo();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

} // end class BorderLayoutDemo

Grid Layout Manager


27
GridLayout allows you to specify a grid size in rows, columns and
optionally pixel spacing between widgets in the rows and columns.
Widgets are added left to right, top to bottom, unless you specify
otherwise via a second int argument to add. That will place your
widget in the Xth position going left to right, top to bottom across
the rows
The Constructors are supported as follows with row and column
giving the number of rows and columns and gap arguments specify the
number of pixels to put between components. Note here that the
default gap is 0 (not 5)

 public GridLayout(itn rows, int columns)

 public GridLayout(int rows, int columns, int horizontalGap, int


verticalGap)

Code Example)

// Fig. 13.26: GridLayoutDemo.java


// Demonstrating GridLayout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GridLayoutDemo extends JFrame implements ActionListener


{
private JButton buttons[];
private final String names[] =
{ "one", "two", "three", "four", "five", "six" };
private boolean toggle = true;
private Container container;
private GridLayout grid1, grid2;

// set up GUI
public GridLayoutDemo()
{
super( "GridLayout Demo" );

// set up layouts
grid1 = new GridLayout( 2, 3, 5, 5 );
grid2 = new GridLayout( 3, 2 );

// get content pane and set its layout


container = getContentPane();
container.setLayout( grid1 );
28

// create and add buttons


buttons = new JButton[ names.length ];

for ( int count = 0; count < names.length; count++ )


{
buttons[ count ] = new JButton( names[ count ] );
buttons[ count ].addActionListener( this );
container.add( buttons[ count ] );
}

setSize( 300, 150 );


setVisible( true );

} // end constructor GridLayoutDemo

// handle button events by toggling between layouts


public void actionPerformed( ActionEvent event )
{
if ( toggle )
container.setLayout( grid2 );
else
container.setLayout( grid1 );

toggle = !toggle; // set toggle to opposite value


container.validate();
}

public static void main( String args[] )


{
GridLayoutDemo application = new GridLayoutDemo();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

} // end class GridLayoutDemo

Card Layout Manager


29
Card Layout allows you to create several different layouts all
overlaid on the same space. You can use some widget to switch
between the layouts for display.

Meta Manipulation methods used to determine which Sub Layout is


currently displayed. The Subcontainer is the reference to the other
layout and a String is the name we give that sublayout for Card
Layout’s purposes.

 void first(SubContainer) moves to the first sub layout you added to


Card Layout

 void next(SubContainer) moves to the next one

 void previous(SubContainer) and back

 void last(SubContainer) last one

 void show(SubContainer, String) pick via name

 void add(SubContainer, String) add a sub layout to the card


layout and give it a name for card layout purposes only

Code Example)

/* CardLayoutDemo.java is a 1.4 application that requires no


other files. */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CardLayoutDemo implements ItemListener


{
JPanel cards; //a panel that uses CardLayout
final static String BUTTONPANEL = "JPanel with JButtons";
final static String TEXTPANEL = "JPanel with JTextField";
30
public void addComponentToPane(Container pane) {

//Put the JComboBox in a JPanel to get a nicer look.


JPanel comboBoxPane = new JPanel(); //use FlowLayout by
default
String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL };
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);

//Create the "cards".


JPanel card1 = new JPanel();
card1.add(new JButton("Button 1"));
card1.add(new JButton("Button 2"));
card1.add(new JButton("Button 3"));

JPanel card2 = new JPanel();


card2.add(new JTextField("TextField", 20));

//Create the panel that contains the "cards".


cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);

pane.add(comboBoxPane, BorderLayout.PAGE_START);
pane.add(cards, BorderLayout.CENTER);
}

public void itemStateChanged(ItemEvent evt)


{
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String)evt.getItem());
}

/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/

private static void createAndShowGUI()


{
//Make sure we have nice window decorations.
31
JFrame.setDefaultLookAndFeelDecorated(true);

//Create and set up the window.


JFrame frame = new JFrame("CardLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.


CardLayoutDemo demo = new CardLayoutDemo();
demo.addComponentToPane(frame.getContentPane());

//Display the window.


frame.pack();
frame.setVisible(true);
}

public static void main(String[] args)


{
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run()


{
createAndShowGUI();
}
}
);
}
}

Chapter 13: Java Applets


32

Java Applets

Applets are Java programs designed to be embedded into a web page.


They can also be launched by typing appletviewer file.html where the
applet is embedded in the file.

 Applets are downloaded from the web page they are embedded in. So
both the web page and the applet end up beign transferred to the
client before running

 Applets need to load the JVM before they can run, which is why they
are uncommon now - the reason? You generally have at most 8 seconds
to grab the viewer’s attention or they will leave a page.

 Applets do not have a main method, but do have additional security


constraints placed on them. File access to local machine, etc.

Applet Usage Here are a few things to be aware of when designing


applets

 Import java.awt.graphics and javax.swing.Japplet

 Super a keyword used in the dot naming convention to indicate use


of a parent’s attribute or method

 Swing provides a wide variety of built in GUI elements such as


menus, combo boxes, etc.

Applet Methods here are the key applet methods

 Init() called when applet is first loaded into browser


33
 Start() Called after init, after this applet goes live and we can
code ongoing behavior

 Paint() Called whenever something happens to change the display of


the applet (window resize, etc). You need to over-ride this method
to include the new code you wish to run (drawing, etc). But you also
need to call the parent’s version of the paint method as well to
handle the code you do not wish to write again by using the super
keyword.

 Stop() Called when browser window becomes invisible. Useful for


turning off features if a window is hidden for example

 Destroy() destructor when applet is no longer needed

Applet Examples

Code1)

<html>
<applet code = "WelcomeApplet.class" width = "300" height = "45">
</applet>
</html>

// A first applet in Java.


// Java packages
import java.awt.Graphics; // import class Graphics
import javax.swing.JApplet; // import class JApplet

public class WelcomeApplet extends JApplet


{

// draw text on applet’s background


public void paint( Graphics g )
{
// call superclass version of method paint
super.paint( g );
34
// draw a String at x-coordinate 25 and y-coordinate 25
g.drawString( "Welcome to Java Programming!", 25, 25 );

} // end method paint

} // end class WelcomeApplet

Code2)

// Fig. 3.9: WelcomeApplet2.java


// Displaying multiple strings in an applet.

// Java packages
import java.awt.Graphics; // import class Graphics
import javax.swing.JApplet; // import class JApplet

public class WelcomeApplet2 extends JApplet


{
// draw text on applet’s background
public void paint( Graphics g )
{
// call superclass version of method paint
super.paint( g );

// draw two Strings at different locations


g.drawString( "Welcome to", 25, 25 );
g.drawString( "Java Programming!", 25, 40 );

} // end method paint


} // end class WelcomeApplet2

<html>
<applet code = "WelcomeApplet2.class" width = "300" height = "60">
</applet>
</html>

Code3)

// Fig. 3.11: WelcomeLines.java


// Displaying text and lines.

// Java packages
import java.awt.Graphics; // import class Graphics
35
import javax.swing.JApplet; // import class JApplet

public class WelcomeLines extends JApplet


{

// draw lines and a string on applet’s background


public void paint( Graphics g )
{
// call superclass version of method paint
super.paint( g );

// draw horizontal line from (15, 10) to (210, 10)


g.drawLine( 15, 10, 210, 10 );

// draw horizontal line from (15, 30) to (210, 30)


g.drawLine( 15, 30, 210, 30 );

// draw String between lines at location (25, 25)


g.drawString( "Welcome to Java Programming!", 25, 25 );

} // end method paint

} // end class WelcomeLines

<html>
<APPLET CODE = "WelcomeLines.class" WIDTH = "300" HEIGHT = "40">
</APPLET>
</html>

Code4)

// Fig. 3.13: AdditionApplet.java


// Adding two floating-point numbers.

// Java packages
import java.awt.Graphics; // import class Graphics
import javax.swing.*; // import package javax.swing

public class AdditionApplet extends JApplet


{
double sum; // sum of values entered by user

// initialize applet by obtaining values from user


36
public void init()
{
String firstNumber; // first string entered by user
String secondNumber; // second string entered by user

double number1; // first number to add


double number2; // second number to add

// obtain first number from user


firstNumber = JOptionPane.showInputDialog(
"Enter first floating-point value" );

// obtain second number from user


secondNumber = JOptionPane.showInputDialog(
"Enter second floating-point value" );

// convert numbers from type String to type double


number1 = Double.parseDouble( firstNumber );
number2 = Double.parseDouble( secondNumber );

// add numbers
sum = number1 + number2;

} // end method init

// draw results in a rectangle on applet’s background


public void paint( Graphics g )
{
// call superclass version of method paint
super.paint( g );

// draw rectangle starting from (15, 10) that is 270


// pixels wide and 20 pixels tall
g.drawRect( 15, 10, 270, 20 );

// draw results as a String at (25, 25)


g.drawString( "The sum is " + sum, 25, 25 );

} // end method paint

} // end class AdditionApplet

<html>
<applet code = "AdditionApplet.class" width = "300" height = "50">
</applet>
</html>
37
Chapter 14: Streams, Files, File Access

Streams

Streams are Java’s means of

You might also like