860 likes | 880 Views
Learn how to create basic applets in Java that print messages and draw shapes. Explore graphics essentials and drawing methods.
E N D
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 CS102 Algorithms and Programming II
A Simple Applet Program (cont.) Output: CS102 Algorithms and Programming II
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 CS102 Algorithms and Programming II
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. CS102 Algorithms and Programming II
Output of ManApplet CS102 Algorithms and Programming II
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. CS102 Algorithms and Programming II
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. } } CS102 Algorithms and Programming II
Coordinate System 0,0 width drawing surface of an applet height width-1,height-1 • Each point on the coordinate system represents a single pixel. • Anything drawn outside of this area will not be visible. CS102 Algorithms and Programming II
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 CS102 Algorithms and Programming II
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); CS102 Algorithms and Programming II
Rectangles drawRect(xsrc,ysrc,width,height) fillRect(xsrc,ysrc,width,height) top left corner CS102 Algorithms and Programming II
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 CS102 Algorithms and Programming II
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 CS102 Algorithms and Programming II
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,90 counter-clockwise (positive) 180,-180 0,360,-360 clockwise (negative) 270,-90 CS102 Algorithms and Programming II
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); CS102 Algorithms and Programming II
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) CS102 Algorithms and Programming II
Polygons (cont.) int[] xs = {50,100,150,100}; 100,50 int[] 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,150 p.addPoint(150,100); p.addPoint(100,150); drawPolygon(p); CS102 Algorithms and Programming II
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); CS102 Algorithms and Programming II
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 CS102 Algorithms and Programming II
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. CS102 Algorithms and Programming II
Color Class - Example public void paint (Graphics g) { setBackground(Color.white); background is white g.setColor(Color.yellow); color of pen is yellow g.drawString(“This is yellow”,20,20); This is yellow g.setColor(Color.blue); color of pen is blue g.drawLine(20,50,200,50); g.setColor(Color.green); color of pen is green g.drawRect(20,100,200,100); } CS102 Algorithms and Programming II
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 CS102 Algorithms and Programming II
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 } } CS102 Algorithms and Programming II
GraphicsTest import 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); } } CS102 Algorithms and Programming II
Output of GraphicsTest CS102 Algorithms and Programming II
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. CS102 Algorithms and Programming II
BannerTest import 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();) ; } } } CS102 Algorithms and Programming II
BallTest import 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();) ; } } } CS102 Algorithms and Programming II
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; } CS102 Algorithms and Programming II
BouncingBallTest – paint method public 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); } CS102 Algorithms and Programming II
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. CS102 Algorithms and Programming II
Component Class Hierachy (some of it) Object Component an abstract class Button Checkbox Choice Label TextComponent TextArea TextField Container a special component, we can put other GUI components into this component Panel Applet Normally we use this class when we implement an applet. Window Frame Normally we use this class to provide GUI from an application Dialog CS102 Algorithms and Programming II
Hierarchy of Swing and AWT Classes CS102 Algorithms and Programming II
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. CS102 Algorithms and Programming II
Simple I/O in Applets import 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); } CS102 Algorithms and Programming II
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(""); } } CS102 Algorithms and Programming II
Simple I/O in Applets (Output) At the beginning Before we push the return key After we pushed the return key CS102 Algorithms and Programming II
Simple I/O in Applets (Output-cont.) Before we push the return key After we pushed the return key CS102 Algorithms and Programming II
Another Applet with I/O Operations import 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); } CS102 Algorithms and Programming II
Another Applet with I/O Operations (cont.) // 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 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); } } CS102 Algorithms and Programming II
Another Applet with I/O Operations (output) CS102 Algorithms and Programming II
What happens when we type a real number? CS102 Algorithms and Programming II
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); } CS102 Algorithms and Programming II
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 minumum if (num1<num2) minValue = num1; else minValue = num2; if (num3<minValue) minValue = num3; // put the new minimum into the applet lMinValue.setText(minValue + ""); } } CS102 Algorithms and Programming II
Another Version (output) Before pushing button After pushing button CS102 Algorithms and Programming II
An Example Applet –With Loops // This applet draw a ladder like shape // The number of the steps is read from a TextField import 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); } CS102 Algorithms and Programming II
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(); } } CS102 Algorithms and Programming II
An Example Applet -- Output CS102 Algorithms and Programming II
BGColor01 import 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); } } CS102 Algorithms and Programming II
BGColor01 -- Output CS102 Algorithms and Programming II