CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October...

86
CS102 Algorithms and Programming II 1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints “Hello, World” import java.awt.*; import java.applet.Applet; public class Test1Applet extends Applet { public void paint (Graphics page) { page.drawString(“Hello, World”, 50,50); } // end of paint method } // end of class

description

CS102 Algorithms and Programming II3 Another Applet Program -- ManApplet.java // A simple applet program which draws a man import java.awt.*; import java.applet.Applet; public class ManApplet extends Applet { public void paint (Graphics page) { page.drawString("A MAN", 100,30); // Head page.drawOval(100,50,50,50); page.drawOval(115,65,5,5); // eyes page.drawOval(130,65,5,5); page.drawLine(125,70,125,80); // nose page.drawLine(120,85,130,85); // mouth // Body page.drawLine(125,100,125,150); // Legs page.drawLine(125,150,100,200); page.drawLine(125,150,150,200); // Hands page.drawLine(125,125, 75,125); page.drawLine(125,125,165,100); } // end of paint method } // end of class

Transcript of CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October...

Page 1: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 1

A Simple Applet Program

// Author: Ilyas Cicekli Date: October 9, 1997//// A simple applet program which prints “Hello, World” import java.awt.*;import java.applet.Applet; public class Test1Applet extends Applet { 

public void paint (Graphics page) { page.drawString(“Hello, World”, 50,50);} // end of paint method

 } // end of class

Page 2: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 2

A Simple Applet Program (cont.)

Output:

Page 3: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 3

Another Applet Program -- ManApplet.java// A simple applet program which draws a man import java.awt.*;import java.applet.Applet; 

public class ManApplet extends Applet { 

public void paint (Graphics page) { page.drawString("A MAN", 100,30); // Head page.drawOval(100,50,50,50); page.drawOval(115,65,5,5); // eyes page.drawOval(130,65,5,5); page.drawLine(125,70,125,80); // nose page.drawLine(120,85,130,85); // mouth // Body page.drawLine(125,100,125,150); // Legs page.drawLine(125,150,100,200); page.drawLine(125,150,150,200); // Hands page.drawLine(125,125, 75,125); page.drawLine(125,125,165,100);} // end of paint method

} // end of class

Page 4: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 4

Another Applet Program (cont.)

drawString(astring,x,y)writes the given string starting from the <x,y> coordinate.

 drawLine(x1,y1,x2,y2)

draws a line from <x1,y1> to <x2,y2> coordinate. drawOval(x,y,width,height)

draws an oval with given width and height (if the oval were enclosed in a rectangle).<x,y> gives the top left corner of the rectangle.

Page 5: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 5

Output of ManApplet

Page 6: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 6

Graphics Class

• Graphics class is a class in java.awt package.– contains methods for creating line drawings, rectangles, ovals, arcs, polygons.– control color and fonts

• A Graphics object represents a particular drawing surface.– We cannot directly call the constructor of Graphics class to create a Graphics

object.– A Graphics object is created indirectly. For example, each applet is associated

with a Graphics object, and we can access this Graphics object.– Any methods called with the Graphics object associated with an applet will affect

that applet.

• An object of Graphics class represents a particular drawing surface, and Graphics class contains methods for drawing shapes on that surface.

Page 7: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 7

An Applet’s Graphics Context

• An applet has a graphics context which is automatically passed to the paint method when it is invoked.

import java.applet.Applet;import java.awt.*;public class AnApplet extends Applet {

public void paint(Graphics g) {… … // using this Graphics object g,… … // we can draw shapes on this applet.

}}

Page 8: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 8

Coordinate System

0,0 width drawing surface of

an appletheight

width-1,height-1

• Each point on the coordinate system represents a single pixel.• Anything drawn outside of this area will not be visible.

Page 9: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 9

An Example

import java.applet.Applet;import java.awt.*;public class AnApplet extends Applet {

public void paint(Graphics g) { g.drawRect(10,10,100,50);

top left corner width and height of the rectangle

g.drawLine(10,10,110,60);

source coordinate destination coordinate

g.drawString(“This a rectangle”,10,150);}

} top left corner

Page 10: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 10

Drawing Shapes

• Graphics class directly supports the drawing of:– lines– ovals (circles are special forms of ovals)– rectangles– arcs– polygons – triangles, hexagons, …– polylines – a series of line segments

• Most shapes (except polylines) can be drawn filled or unfilled.

– We can see the other graphics objects under an unfilled object

– The foreground color is used to fill shapes. The other graphics objects under a filled object cannot be seen.

• Thickness cannot be specified (always 1 pixel). Thicker lines can be drawn by multiple lines.

g.drawLine(10,10,200,10);g.drawLine(10,11,200,11);

Page 11: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 11

Rectangles

drawRect(xsrc,ysrc,width,height)fillRect(xsrc,ysrc,width,height)

top left corner

Page 12: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 12

Ovals

• A bounding rectangle is used to define the position of an oval.

drawRect(xsrc,ysrc,width,height)fillRect(xsrc,ysrc,width,height)

top left corner of the bounding rectangle

bounding rectangle is not seen

• if width and height are equal a circle

Page 13: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 13

Some Other Rectangle Related Methods

clearRect(x,y,width,height)draws a (filled) rectangle in the current background color.cleans that rectangle area.

drawRoundRect(x,y,width,height,arcwidth,archeight)fillRoundRect(x,y,width,height,arcwidth,archeight)

draws a rectangle with rounded corners.

archeight arcwidth

Page 14: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 14

Arcs

• An arc is a segment of an oval.• The segment begins at a specific angle, and extends for a distance

specified by the arc angle.

drawArc(x,y,width,height,startangle,arcangle)fillArc(x,y,width,height,startangle,arcangle)

-270,90counter-clockwise (positive)

180,-180 0,360,-360clockwise (negative)

270,-90

Page 15: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 15

Arcs (cont.)

• startangle is in degrees – – a value between 0 and 360, or between 0 and -360

• arcangle– positive (counter clockwise)– negative (clockwise)

drawArc(20,20,50,50,90,90);drawArc(20,20,50,50,-270,90);drawArc(20,20,50,50,180,-90);drawArc(20,20,50,50,-180,-90); same arc is drawn by all of them

fillArc(20,20,50,50,90,90);

Page 16: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 16

Polygons

• A polygon is a multi-sided figure• A polygon is defined using a series of <x,y> points which indicates the

end points of the sides of that polygon.• Polygons are closed. It forms a line segment from the last point to the

first.• End points can be specified by:

– two integer arrays or– an object of Polygon class indicating the end points.

drawPolygon(int[] xpoints, int[] ypoints, int numofpoints)fillPolygon(int[] xpoints, int[] ypoints, int numofpoints)drawPolygon(Polygon poly)fillPolygon(Polygon poly)

Page 17: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 17

Polygons (cont.)

int[] xs = {50,100,150,100}; 100,50int[] ys = {100,50,100,150};drawPolygon(xs,ys,4);

50,100 150,100

Polygon p = new Polygon();p.addPoint(50,100);p.addPoint(100,50); 100,150p.addPoint(150,100);p.addPoint(100,150);drawPolygon(p);

Page 18: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 18

Polyline

• A polyline is a similar to a polygon except it is not closed.• There is no line segment from the last point to the first one.• Polylines cannot be filled.

int[] xs = {50,100,150,100};int[] ys = {100,50,100,150};drawPolyline(xs,ys,4);

Page 19: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 19

Color Class

• Color class is used to define and manage the color in which shapes are drawn.

• We can control the color of the shapes we draw.• A color is defined by an R G B value (red,green,blue) that specifies

the relative contribution of these three primary colors red, green, blue (values between 0 to 255).

• Color class contains several final static Color objects to define basic colors.– blue Color.blue 0,0,255– green Color.green 0,255,0– red Color.red 255,0,0– black Color.black 0,0,0– white Color.white 255,255,255– yellow Color.yellow 255,255,0– gray Color.gray 128,128,128

Page 20: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 20

Color Class (cont.)

• In addition to basic colors defined in Color class, we can define our own color by setting these three values (2563 – almost 16 million different colors).

Color mycolor = new Color(100,100,100);

• We can change foreground (colors of shapes) and background (general color of the applet) colors. In paint method,

setBackground(Color.white)changes the background color to white. setBackground is a method of Applet class.

g.setColor(Color.red)changes the foreground color to red. setColor is a method of Graphics class.

Page 21: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 21

Color Class - Example

public void paint (Graphics g) {setBackground(Color.white); background is white

g.setColor(Color.yellow); color of pen is yellowg.drawString(“This is yellow”,20,20); This is yellow

g.setColor(Color.blue); color of pen is blueg.drawLine(20,50,200,50);

g.setColor(Color.green); color of pen is greeng.drawRect(20,100,200,100);

}

Page 22: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 22

Fonts

• A font defines the look of each character when it is printed or drawn.• Font class provides methods for specifying fonts in a Java program.• There is a specific set of fonts in each system. We can use one of the

fonts from this list.• Using the constructor of Font class we can create a Font object.• Then we can set the current font to this Font object using setFont

method in Graphics class.

new Font(fontname,style,size)

“TimesRoman” Font.PLAIN 12 14 16 18 20 …“Helvetica” Font.BOLD

Font.ITALIC

Page 23: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 23

Fonts -- Example

import java.applet.Applet;import java.awt.*;public class FontTest extends Applet { public void paint(Graphics g) { g.setFont(new Font("TimesRoman",Font.PLAIN,16)); g.drawString("Font is TimesRoman-PLAIN-16",10,30);

Font is TimesRoman-PLAIN-16 g.setFont(new Font("TimesRoman",Font.ITALIC,20)); g.drawString("Font is TimesRoman-ITALIC-20",10,60);

Font is TimesRoman-ITALIC-20 g.setFont(new Font(“Courier",Font.BOLD+Font.ITALIC,20));

g.drawString("Font is Courier-BOLD-ITALIC-20",10,90); Font is Courier-BOLD-ITALIC-20

g.setFont(new Font("Courier",Font.PLAIN,16)); g.drawString("Font is Courier-PLAIN-16",10,120);

Font is Courier-PLAIN-16 }}

Page 24: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 24

GraphicsTestimport java.applet.Applet;import java.awt.*;public class GraphicsTest extends Applet { public void paint(Graphics g) { resize(600,400); g.drawRect(10,10,200,100); g.drawLine(10,10,210,110); g.drawLine(10,110,210,10); g.drawString("This is a rectangle",10,130); g.setColor(Color.red); g.drawString("A red string",10,150); g.setColor(Color.blue); g.drawString("A blue string",10,170); g.fillRect(300,10,100,50); g.drawOval(300,100,100,50); g.fillOval(300,200,100,50); g.drawOval(300,300,40,40); g.fillOval(350,300,40,40); }}

Page 25: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 25

Output of GraphicsTest

Page 26: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 26

Animation

• Simple animations can be accomplished by drawing a shape, then erasing it. Then drawing it again in a slightly altered position.

• Timing must be controlled so that animation does not move too fast.

Page 27: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 27

BannerTestimport java.applet.Applet;import java.awt.*;public class BannerTest extends Applet { private final String BANNER="Ilyas Cicekli"; private int WIDTH; private final int DELAY=30; public void init() { Dimension d; d = getSize(); WIDTH = d.width; } public void paint(Graphics g) { int i=1; long currtime; for (;;i++) { if (i%WIDTH==0) i=0; g.clearRect(0,0,WIDTH,100); g.drawString(BANNER,i,20); // Wait DELAY for (currtime=System.currentTimeMillis(); currtime+DELAY>System.currentTimeMillis();) ; } }}

Page 28: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 28

BallTestimport java.applet.Applet;import java.awt.*;public class BallTest extends Applet { private int WIDTH,HEIGHT; private int BALLSIZE=1; private final int DELAY=50; public void init() { Dimension d; d = getSize(); WIDTH = d.width; HEIGHT = d.height; } public void paint(Graphics g) { int i; if (WIDTH<HEIGHT) i=WIDTH/2; else i=HEIGHT/2; long currtime; g.setColor(Color.red); for (;i>0;i=i-3,BALLSIZE=BALLSIZE+6) { g.drawOval(i,i,BALLSIZE,BALLSIZE); // Wait DELAY for (currtime=System.currentTimeMillis(); currtime+DELAY>System.currentTimeMillis();) ; } }}

Page 29: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 29

BouncingBallTest

import java.awt.*;import java.applet.Applet;

public class BouncingBallTest extends Applet { private final int INC=1; private final long WTIME = 30; private final int BALLSIZE=15; private int WIDTH, HEIGHT; public void init() { Dimension d;

resize(700,250); d = getSize(); WIDTH = d.width; HEIGHT = d.height; }

Page 30: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 30

BouncingBallTest – paint methodpublic void paint(Graphics g) { long currtm; int x=0, y=HEIGHT-100-BALLSIZE, yinc=0; int radius,j; g.drawLine(0,HEIGHT-99,WIDTH,HEIGHT-99); g.drawLine(0,HEIGHT-98,WIDTH,HEIGHT-98); g.drawLine(0,HEIGHT-97,WIDTH,HEIGHT-97); g.setColor(Color.red); g.drawString("StartTime: "+System.currentTimeMillis(),10,HEIGHT-80); g.fillOval(x,y-yinc,BALLSIZE,BALLSIZE); for (radius=80; radius>0; radius-=10) { for (j=-radius+1; j<=radius; j++) { for(currtm=System.currentTimeMillis(); currtm+WTIME > System.currentTimeMillis(); ) ;

g.clearRect(0,0,WIDTH,HEIGHT-100); g.fillOval(x,y-yinc,BALLSIZE,BALLSIZE); x++; yinc = (int) Math.sqrt((radius*radius)-(j*j)); } } g.drawString("EndTime: "+System.currentTimeMillis(),10,HEIGHT-60);}

Page 31: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 31

GUI (Graphical User Interface)

• Today’s modern software includes a graphical user interface (GUI).– user can interact with a program using a GUI.

• A GUI is composed of many pieces.• Java provides a set of classes derived from Component class to

construct GUIs.• These classes are available in java.awt package.

Page 32: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 32

Component Class Hierachy (some of it)

ObjectComponent an abstract class

ButtonCheckboxChoiceLabelTextComponentTextAreaTextFieldContainer a special component, we can put other GUI components into this component

PanelApplet Normally we use this class when we implement an applet.

WindowFrame Normally we use this class to provide GUI from an application

Dialog

Page 33: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 33

Hierarchy of Swing and AWT Classes

Page 34: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 34

GUI

• Arranging components in a container is the job of layout managers.– The layout manager decides where to put a component in a container.– A container can be put into another container too.– The default layout manager in applets is FlowLayout.

• After we arrange our components in a container, we will have a visual representation of a program.

• Depending on a specific program, when the user presses a button, types a key, or moves the mouse, an event is issued.

• The program should respond to these events (if it wants).• Event-driven programming is a technique used in the development of

the software. The program operates in response to events as they occur.

Page 35: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 35

Simple I/O in Appletsimport java.awt.*;import java.applet.*;import java.awt.event.*;

public class HiMessageApplet extends Applet implements ActionListener { Label prompt,greeting; // Output areas TextField input; // Input area // This method will be called when the applet starts, // and creates the required parts of the applet. public void init() { // Create prompt area and put it into the applet prompt = new Label("Enter your name and push return key: "); add(prompt); // Create input area and put it into the applet input = new TextField(20); add(input); // Create greeting area and put it into the applet greeting = new Label(""); add(greeting); // "this" (this applet) will listen the input area and // respond the events in this area. input.addActionListener(this); }

Page 36: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 36

Simple I/O in Applets (cont.)

// This method will be called when anytime a string is typed // in input area and the return key is pushed. public void actionPerformed(ActionEvent e) { greeting.setSize(300,20); greeting.setText("Hi " + input.getText()); input.setText(""); }}

Page 37: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 37

Simple I/O in Applets (Output)

At the beginning

Before we push the return key

After we pushed the return key

Page 38: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 38

Simple I/O in Applets (Output-cont.)

Before we push the return key

After we pushed the return key

Page 39: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 39

Another Applet with I/O Operationsimport java.applet.Applet; import java.awt.*; import java.awt.event.*; public class SumAverageApplet extends Applet implements ActionListener {

Label prompt; // prompt area TextField input; // input area for positive integer int number; // value of positive integer int sum; // sum of all numbers int count; // number of positive integers double average; // average of all numbers

// Create the graphical components and initialize the variables public void init() { // Create prompt and put it into the applet prompt = new Label( "Enter a positive integer and push the return key:" ); add(prompt); // Create input area and put it into the applet input = new TextField(10); add(input); // Initialize the variables sum = 0; count = 0; // this applet will listen input area and respond to the events hapenning in this area input.addActionListener(this); }

Page 40: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 40

Another Applet with I/O Operations (cont.) // Respond to the events in input areapublic void actionPerformed(ActionEvent e) { // Get the input and convert it into a number number = Integer.parseInt(e.getActionCommand().trim()); // Evaluate the new values sum = sum + number; count = count + 1;

average = (double) sum / count; input.setText("");

// show the results repaint();}

// Show the results public void paint(Graphics g) { g.drawString("SUM : " + Integer.toString(sum), 50, 50); g.drawString("AVG : " + Double.toString(average), 50, 70); g.drawString("COUNT : " + Integer.toString(count), 50, 90);}

}

Page 41: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 41

Another Applet with I/O Operations (output)

Page 42: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 42

What happens when we type a real number?

Page 43: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 43

An Example Program with If-Statements// Finding the minumum of three integers import java.applet.Applet; import java.awt.*;import java.awt.event.*;

public class MinTestApplet extends Applet implements ActionListener { TextField tNum1,tNum2,tNum3; // text fields for indegers Button b; Label lMinValue; // Area for the minimum number int minValue,num1,num2,num3; // Create fields and initialize the variables public void init() {

// Initialize variables minValue = 0; num1 = 0; num2 = 0; num3 = 0; // Create input areas

b = new Button("Find Minimum"); add(b); add(new Label("First Number: ")); tNum1=new TextField("0",10); add(tNum1);

add(new Label("Second Number: ")); tNum2=new TextField("0",10); add(tNum2); add(new Label("Third Number: ")); tNum3=new TextField("0",10); add(tNum3); // create output area add(new Label("Minimum Value: ")); lMinValue=new Label("0"); add(lMinValue); // Listen the button b.addActionListener(this);

}

Page 44: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 44

An Example Applet with If-Statements (cont.)

// Respond to the events public void actionPerformed(ActionEvent e) {

num1 = Integer.parseInt(tNum1.getText().trim()); num2 = Integer.parseInt(tNum2.getText().trim()); num3 = Integer.parseInt(tNum3.getText().trim());

// find the minumumif (num1<num2) minValue = num1; else minValue = num2;

if (num3<minValue) minValue = num3;

// put the new minimum into the appletlMinValue.setText(minValue + "");

} }

Page 45: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 45

Another Version (output)

Before pushingbutton

After pushingbutton

Page 46: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 46

An Example Applet –With Loops// This applet draw a ladder like shape// The number of the steps is read from a TextFieldimport java.awt.*;import java.applet.Applet;import java.awt.event.*;

public class Ladder extends Applet implements ActionListener{ private final int MAXSTEPS = 30; private int numOfSteps = 0; private TextField input; // Create components and put them into the applet public void init() {

add(new Label("Number of Steps: ")); input = new TextField(10); add(input); input.addActionListener(this);

}

Page 47: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 47

An Example Applet (cont.) // Draw the ladder like shape public void paint(Graphics g) {

int i; int x=20, y=20; for (i=0; i<numOfSteps; i=i+1) {

g.drawLine(x,y,x+20,y); g.drawLine(x+20,y,x+20,y+20); x=x+20; y=y+20;

} }

// Read the number of steps and activate paint method public void actionPerformed(ActionEvent e) {

numOfSteps = Integer.parseInt(e.getActionCommand().trim()); if (numOfSteps>MAXSTEPS)

numOfSteps = MAXSTEPS; else if (numOfSteps<0)

numOfSteps = 0; repaint();

} }

Page 48: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 48

An Example Applet -- Output

Page 49: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 49

BGColor01import java.awt.*;import java.awt.event.*;import java.applet.Applet;public class BGColor01 extends Applet implements ActionListener { private Button b1=new Button("Red"), b2=new Button("Green"),

b3=new Button("Blue"); private TextField t=new TextField(100); public void init() { add(t); add(b1); add(b2); add(b3); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); } public void actionPerformed(ActionEvent e) { t.setText(e.toString()); if (e.getSource() == b1) setBackground(Color.red); else if (e.getSource() == b2) setBackground(Color.green); else if (e.getSource() == b3) setBackground(Color.blue); }}

Page 50: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 50

BGColor01 -- Output

Page 51: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 51

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

public class BGColor02Swing extends JFrame implements ActionListener { private JButton b1 = new JButton("Red"), b2 = new JButton("Green"), b3 = new JButton("Blue");

public BGColor02Swing() { // Set the title of the frame setTitle("BGColor-02"); // Frame size setSize(600,200); // Set layout to FlowLayout setLayout(new FlowLayout()); // ARRANGE GUI add(b1); add(b2); add(b3); // ADD LISTENERS b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); }

Page 52: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 52

BGColor02

public static void main(String args[]) { BGColor02Swing f = new BGColor02Swing(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); }

// Action Listener public void actionPerformed(ActionEvent e) { if (e.getSource() == b1) this.getContentPane().setBackground(Color.RED); else if (e.getSource() == b2) this.getContentPane().setBackground(Color.green); else if (e.getSource() == b3) this.getContentPane().setBackground(Color.blue); repaint(); }

Page 53: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 53

BGColor Menuimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class BGCMenu extends JFrame implements ActionListener, WindowListener { public BGCMenu() { // Set the title of the frame setTitle("BGColor-CheckboxSwing"); setLayout(new FlowLayout()); setSize(600,300); // ARRANGE GUI JMenu colorMenu = new JMenu("Add Colors"); JMenuItem redChoice = new JMenuItem("Red"); colorMenu.add(redChoice); JMenuItem greenChoice = new JMenuItem("Green"); colorMenu.add(greenChoice); JMenuItem blueChoice = new JMenuItem("Blue"); colorMenu.add(blueChoice); JMenuBar bar = new JMenuBar(); bar.add(colorMenu); setJMenuBar(bar); // ADD LISTENERS redChoice.addActionListener(this); greenChoice.addActionListener(this); blueChoice.addActionListener(this); addWindowListener(this); }

Page 54: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 54

BGColor Menu public static void main(String args[]) { BGCMenu f = new BGCMenu(); f.setVisible(true); } // Action Listener public void actionPerformed(ActionEvent e) {

String buttonStr = e.getActionCommand(); if (buttonStr.equals("Red")) this.getContentPane().setBackground(Color.RED); else if (buttonStr.equals("Green")) this.getContentPane().setBackground(Color.green); else if (buttonStr.equals("Blue")) this.getContentPane().setBackground(Color.blue); repaint(); } // Window Listener public void windowClosing(WindowEvent e) {System.exit(0);} public void windowOpened(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {}}

Page 55: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 55

SumAverage – Label and TextField

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

public class SumAverageSwing extends JFrame implements ActionListener, WindowListener {

JLabel prompt,result; // prompt area JTextField input; // input area for positive integer

int number; // value of positive integer int sum; // sum of all numbers int count; // number of positive integers double average; // average of all numbers

Page 56: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 56

SumAverage – Label and TextField public SumAverageSwing() {

setTitle("SumAverageSwing"); setSize(600,300); setLayout(new FlowLayout()); // Create prompt and put it into the applet prompt = new JLabel( "Enter a positive integer and push the return key:" ); add(prompt); // Create input area and put it into the applet input = new JTextField(10); add(input); result = new JLabel( "SUM: AVG: COUNT: " ); add(result); // Initialize the variables sum = 0; count = 0; // "this" will listen input area and // respond to the events hapening in this aarea input.addActionListener(this); addWindowListener(this);

}

Page 57: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 57

SumAverage – Label and TextField

public static void main(String args[]){ SumAverageSwing f = new SumAverageSwing(); f.setVisible(true); } // Respond to the events in input area public void actionPerformed(ActionEvent e) {

// Get the input and convert it into a number number = Integer.parseInt(e.getActionCommand().trim()); // Evaluate the new values sum = sum + number; count = count + 1; average = (double) sum / count; input.setText(""); // show the results result.setText("SUM: " + sum + " " + "AVG: "+average

+ " " + "COUNT: "+count); }

Page 58: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 58

Labels

• A label defines a line of text displayed on a GUI• Labels are static in the sense that they cannot be selected or modified by

the human user once added to a container• A label is instantiated from the JLabel class• The JLabel class contains several constructors and methods for

setting up and modifying a label's content and alignmentJLabel(label)JLabel(label,alignment) where label is a string andsetText(label) alignment is LEFT,RIGHT, or CENTER

Page 59: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 59

Text Fields and Text Areas

• A text field displays a single line of text in a GUI• It can be made editable, to get input from the user• A text area is similar, but displays multiple lines of text• They are defined by the JTextField and JTextArea classes• A text area automatically has scrollbars on its bottom and right sides

JTextField(columns)JTextField(text,columns)JTextArea(rows,columns)JTextArea(text,rows,columns)setText(text)getText()

Page 60: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 60

Layout Managers

• Some of predefined layout managers in the java.awt package:– flow layout– border layout– grid layout

• Each container has a particular layout manager associated with it by default

• A programmer can also create custom layout managers

Page 61: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 61

Flow Layout

• Components are placed in a row from left to right in the order in which they are added

• A new row is started when no more components can fit in the current row

• The components are centered in each row by default• The programmer can specify the size of both the vertical and horizontal

gaps between the components• Flow layout is the default layout for panels and applets

Page 62: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 62

FlowLayoutTestimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class FlowLayoutTest extends JFrame { private JButton b1 = new JButton("Red"), b2 = new JButton("Green"), b3 = new JButton("Blue"), b4 = new JButton("Yellow"), b5 = new JButton("Pink"); public FlowLayoutTest() {

setTitle("FlowLayout Test");setLayout(new FlowLayout());setSize(600,200);add(b1); add(b2); add(b3); add(b4); add(b5);

} public static void main(String args[]) { JFrame f = new FlowLayoutTest(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); }}

Page 63: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 63

FlowLayoutTest -- Snapshots

Page 64: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 64

Border Layout

• Defines five locations each of which a component or components can be added– North, South, East, West, and Center

• The programmer specifies the area in which a component should appear

• The relative dimensions of the areas are governed by the size of the components added to them

Page 65: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 65

Border Layout (cont.)

North

South

West EastCenter

Page 66: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 66

BorderLayoutTestimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class BorderLayoutTest extends JFrame { private JButton b1 = new JButton("Red"), b2 = new JButton("Green"), b3 = new JButton("Blue"),b4 = new JButton("Yellow"), b5 = new JButton("Pink"); public BorderLayoutTest() { // Set the title of the frame, Set layout manger, Frame size setTitle("BorderLayout Test"); setLayout(new BorderLayout()); setSize(600,200); // ARRANGE GUI add(b1,"North"); add(b2,"South"); add(b3,"East"); add(b4,"West"); add(b5,"Center"); }

public static void main(String args[]) { JFrame f = new BorderLayoutTest(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } }

Page 67: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 67

BorderLayoutTest -- Snapshots

Page 68: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 68

Grid Layout

• Components are placed in a grid with a user-specified number of columns and rows

• Each component occupies exactly one grid cell• Grid cells are filled left to right and top to bottom• All cells in the grid are the same size

Page 69: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 69

GridLayoutTestimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class GridLayoutTest extends JFrame { private JButton b1 = new JButton("Red"), b2 = new JButton("Green"), b3 = new JButton("Blue"),b4 = new JButton("Yellow"), b5 = new JButton("Pink"); public GridLayoutTest() {

setTitle("GridLayout Test"); setLayout(new GridLayout(2,3)); setSize(600,200); add(b1);add(b2);add(b3);add(b4);add(b5); } public static void main(String args[]) { JFrame f = new GridLayoutTest(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); }}

Page 70: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 70

GridLayoutTest -- Snapshots

Page 71: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 71

PanelTest

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

public class PanelTest extends JFrame {

public PanelTest() { // Set the title of the frame, Set layout manger, Frame size setTitle("Panel Test"); setLayout(new FlowLayout()); setSize(600,400);

// Arrange GUI JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); JPanel p3 = new JPanel();

Page 72: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 72

PanelTest (cont.) p1.setLayout(new GridLayout(3,1)); p1.add(new JButton("JButton-P1-1")); p1.add(new JButton("JButton-P1-2")); p1.add(new JButton("JButton-P1-3")); p2.setLayout(new GridLayout(3,3)); p2.add(new JButton("JButton-P2-1")); p2.add(new JButton("JButton-P2-2")); p2.add(new JButton("JButton-P2-3")); p2.add(new JButton("JButton-P2-4")); p2.add(new JButton("JButton-P2-5")); p2.add(new JButton("JButton-P2-6")); p2.add(new JButton("JButton-P2-7")); p3.setLayout(new BorderLayout()); p3.add(new JButton("JButton-P3-1"),"North"); p3.add(new JButton("JButton-P3-2"),"South"); p3.add(new JButton("JButton-P3-3"),"East"); p3.add(new JButton("JButton-P3-4"),"West"); p3.add(new JButton("JButton-P3-5"),"Center"); add(p1); add(p2); add(p3); } public static void main(String args[]) { JFrame f = new PanelTest(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); }

Page 73: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 73

PanelTest -- Snapshots

Page 74: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 74

A Text Area With Scroll Barsimport javax.swing.JFrame;import javax.swing.JTextArea;import javax.swing.JPanel;import javax.swing.JLabel;import javax.swing.JButton;import javax.swing.JScrollPane;import java.awt.BorderLayout;import java.awt.FlowLayout;import java.awt.Color;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;

public class ScrollBarDemo extends JFrame implements ActionListener { public static final int WIDTH = 600; public static final int HEIGHT = 400; public static final int LINES = 15; public static final int CHAR_PER_LINE = 30;

private JTextArea memoDisplay; private String memo1; private String memo2;

Page 75: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 75

A Text Area With Scroll Bars public ScrollBarDemo( ) { super("Scroll Bars Demo"); setSize(WIDTH, HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel buttonPanel = new JPanel( ); buttonPanel.setBackground(Color.LIGHT_GRAY); buttonPanel.setLayout(new FlowLayout( )); JButton memo1Button = new JButton("Save Memo 1"); memo1Button.addActionListener(this); buttonPanel.add(memo1Button); JButton memo2Button = new JButton("Save Memo 2"); memo2Button.addActionListener(this); buttonPanel.add(memo2Button); JButton clearButton = new JButton("Clear"); clearButton.addActionListener(this); buttonPanel.add(clearButton); JButton get1Button = new JButton("Get Memo 1"); get1Button.addActionListener(this); buttonPanel.add(get1Button);

Page 76: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 76

A Text Area With Scroll Bars JButton get2Button = new JButton("Get Memo 2"); get2Button.addActionListener(this); buttonPanel.add(get2Button); add(buttonPanel, BorderLayout.SOUTH); JPanel textPanel = new JPanel( ); textPanel.setBackground(Color.BLUE);

memoDisplay = new JTextArea(LINES, CHAR_PER_LINE); memoDisplay.setBackground(Color.WHITE);

JScrollPane scrolledText = new JScrollPane(memoDisplay); scrolledText.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scrolledText.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

textPanel.add(scrolledText);

add(textPanel, BorderLayout.CENTER); }

Page 77: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 77

A Text Area With Scroll Bars public static void main(String[] args){ ScrollBarDemo gui = new ScrollBarDemo( ); gui.setVisible(true); }

public void actionPerformed(ActionEvent e){ String actionCommand = e.getActionCommand( ); if (actionCommand.equals("Save Memo 1")) memo1 = memoDisplay.getText( ); else if (actionCommand.equals("Save Memo 2")) memo2 = memoDisplay.getText( ); else if (actionCommand.equals("Clear")) memoDisplay.setText(""); else if (actionCommand.equals("Get Memo 1")) memoDisplay.setText(memo1); else if (actionCommand.equals("Get Memo 2")) memoDisplay.setText(memo2); else memoDisplay.setText("Error in memo interface"); }

Page 78: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 78

Visibility Demoimport javax.swing.JFrame;import javax.swing.ImageIcon;import javax.swing.JPanel;import javax.swing.JLabel;import javax.swing.JButton;import java.awt.BorderLayout;import java.awt.FlowLayout;import java.awt.Color;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;

public class VisibilityDemo extends JFrame implements ActionListener { public static final int WIDTH = 300; public static final int HEIGHT = 200; private JLabel wavingLabel; private JLabel standingLabel;

public static void main(String[] args){ VisibilityDemo demoGui = new VisibilityDemo( ); demoGui.setVisible(true); }

Page 79: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 79

Visibility Demo public VisibilityDemo( ) { setSize(WIDTH, HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("Visibility Demonstration"); setLayout(new BorderLayout( )); JPanel picturePanel = new JPanel( ); picturePanel.setBackground(Color.WHITE); picturePanel.setLayout(new FlowLayout( )); ImageIcon dukeStandingIcon = new ImageIcon("duke_standing.gif"); standingLabel = new JLabel(dukeStandingIcon); standingLabel.setVisible(true); picturePanel.add(standingLabel); ImageIcon dukeWavingIcon = new ImageIcon("duke_waving.gif"); wavingLabel = new JLabel(dukeWavingIcon); wavingLabel.setVisible(false); picturePanel.add(wavingLabel); add(picturePanel, BorderLayout.CENTER);

Page 80: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 80

Visibility Demo

JPanel buttonPanel = new JPanel( ); buttonPanel.setBackground(Color.LIGHT_GRAY); buttonPanel.setLayout(new FlowLayout( ));

JButton waveButton = new JButton("Wave"); waveButton.addActionListener(this); buttonPanel.add(waveButton);

JButton stopButton = new JButton("Stop"); stopButton.addActionListener(this); buttonPanel.add(stopButton);

add(buttonPanel, BorderLayout.SOUTH); }

Page 81: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 81

Visibility Demo public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand( );

if (actionCommand.equals("Wave")) { wavingLabel.setVisible(true); standingLabel.setVisible(false); } else if (actionCommand.equals("Stop")) { standingLabel.setVisible(true); wavingLabel.setVisible(false); } else System.out.println("Unanticipated error."); }

Page 82: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 82

Inner Classimport javax.swing.JFrame;import javax.swing.JPanel;import java.awt.BorderLayout;import java.awt.FlowLayout;import java.awt.Color;import javax.swing.JLabel;import javax.swing.JButton;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import java.awt.event.WindowListener;import java.awt.event.WindowEvent;

public class WindowListenerDemo3 extends JFrame implements WindowListener{ public static final int WIDTH = 300; //for main window public static final int HEIGHT = 200; //for main window public static final int SMALL_WIDTH = 200; //for confirm window public static final int SMALL_HEIGHT = 100;//for confirm window

Page 83: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 83

Inner Class private class ConfirmWindow extends JFrame implements ActionListener { public ConfirmWindow( ) { setSize(SMALL_WIDTH, SMALL_HEIGHT); getContentPane( ).setBackground(Color.YELLOW); setLayout(new BorderLayout( )); JLabel confirmLabel = new JLabel( "Are you sure you want to exit?"); add(confirmLabel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel( ); buttonPanel.setBackground(Color.ORANGE); buttonPanel.setLayout(new FlowLayout( )); JButton exitButton = new JButton("Yes"); exitButton.addActionListener(this); buttonPanel.add(exitButton); JButton cancelButton = new JButton("No"); cancelButton.addActionListener(this); buttonPanel.add(cancelButton); add(buttonPanel, BorderLayout.SOUTH); }

Page 84: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 84

Inner Class public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand( );

if (actionCommand.equals("Yes")) System.exit(0); else if (actionCommand.equals("No")) dispose( );//Destroys only the ConfirmWindow. else System.out.println( "Unexpected Error in Confirm Window."); } } //End of inner class ConfirmWindow

Page 85: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 85

Inner Class public static void main(String[] args) { WindowListenerDemo3 demoWindow = new WindowListenerDemo3( ); demoWindow.setVisible(true); } public WindowListenerDemo3( ) { setSize(WIDTH, HEIGHT); setTitle("Window Listener Demonstration");

setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(this);

getContentPane( ).setBackground(Color.LIGHT_GRAY); JLabel aLabel = new JLabel("I like to be sure you are sincere."); add(aLabel); }

Page 86: CS102 Algorithms and Programming II1 A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints.

CS102 Algorithms and Programming II 86

Inner Class //The following are now methods of the class WindowListenerDemo3: public void windowOpened(WindowEvent e){}

public void windowClosing(WindowEvent e) { ConfirmWindow checkers = new ConfirmWindow( ); checkers.setVisible(true); }

public void windowClosed(WindowEvent e) {}

public void windowIconified(WindowEvent e){}

public void windowDeiconified(WindowEvent e){}

public void windowActivated(WindowEvent e){}

public void windowDeactivated(WindowEvent e){}}