Java Applet Prepared by Fitsum Introduction Java programs are of two distinct types: applications applets Both types are programs. The difference is that an application is a completely free-standing program. That means it is not part of any other program and it doesn’t need any other program to launch it. In contrast an applet is invoked as part of a Web page and therefore needs either a Web browser or an applet viewer to invoke it. Graphics Applet can be used to display animated images Java graphics are based on pixels. A pixel is a small dot on the screen which can be set to a particular color. Each pixel is identified by a pair of numbers (its coordinates), starting from zero: The horizontal position is, often referred to as x in mathematics (and in java documentation) – this value increases from left to right. The vertical postion, often referred to as y – increases downwards. Java provides us with facilities for drawing: Rectangles, ovals (hence circles), arcs, raised (three-dimensional) rectangles, rectangles with rounded corners, polygons. Additionally, the shapes can be filled with a specified color. Here is the list of the parameters for rectangle and oval. drawRect - the horizontal value of the top left corner. - the vertical value of the top left corner. - the with of the rectangle. - the height of the rectangle. drawOval Imagine the oval squeezed inside a rectangle. - the horizontal value of the top left corner of the rectangle. - the vertical value of the top left corner of the rectangle. - the width of the rectangle. - the height of the rectangle. Example1 import java.awt.*; import java.applet.Applet; public class Example1 extends Applet{ public void paint (Graphics g){ g.drawRect(30,30,80,40); g.drawOval(120,30, 50,50); g.setColor(Color.blue); g.fillRect(30,100, 80,40); g.setColor(Color.orange); g.fillOval(120,100,50,50); g.drawLine(30,160,130,170); } } <title> Example1 </title> <applet code="Example1.class" width= 300 height=200></applet> Methods and Parameters Large programs can be complex, with the result that they can be difficult to understand and debug. The most significant technique for reducing complexity is to split a into isolated sections called methods. Example2 import java.awt.*; import java.applet.Applet; public class Example2 extends Applet{ public void paint(Graphics g){ drawHouse(g, 50,50,70,30); drawHouse(g, 100,50,60,20); } private void drawTriangle(Graphics g, int bottomX, int bottomY, int base, int height){ g.drawLine(bottomX, bottomY, bottomX+base, bottomY); g.drawLine(bottomX+base, bottomY, bottomX + base/2, bottomYheight); g.drawLine(bottomX+base/2, bottomY-height,bottomX, bottomY); } private void drawHouse(Graphics g, int bottomX, int bottomY, int width, int height){ g.setColor(Color.cyan); g.drawRect(bottomX, bottomY-height, width, height); g.setColor(Color.orange); drawTriangle(g, bottomX, bottomY-height, width, height/2); } } HTML code to invoke the program <title> Example2 </title> <applet code="Example2.class" width= 300 height=200></applet> Output Events In programming an event is (in most cases) an action taken by the user. i. Scrollbar events - AdjustmentListener First we need to state that we are going to implement a listener for scrollbar events, which are classified in AdjustmentListener. We then register our program as a listener by using the addAdjustmentListener method, which is in effect causes our simple program, our adjustmentValueChanged method simply fetches the new value from the scrollbar, and arranges for it to be painted on the screen. Example3 (How to use scrollbars) import java.awt.*; import java.applet.Applet; import java.awt.event.*; public class Example3 extends Applet implements AdjustmentListener { private Scrollbar red; private Scrollbar green; private Scrollbar blue; private int redValue = 0; private int greenValue = 0; private int blueValue = 0; public void init() { Label l1, l2, l3; l1 = new Label("Red:"); l2 = new Label("Green:"); l3 = new Label("Blue:"); red = new Scrollbar(Scrollbar.VERTICAL, 0, 0, 0, 256); green = new Scrollbar(Scrollbar.VERTICAL, 0, 0, 0, 256); blue = new Scrollbar(Scrollbar.VERTICAL, 0, 0, 0, 256); add(l1); add(red); add(l2); add(green); add(l3); add(blue); red.addAdjustmentListener(this); green.addAdjustmentListener(this); blue.addAdjustmentListener(this); } public void adjustmentValueChanged(AdjustmentEvent e) { Color c1; redValue = red.getValue(); greenValue = green.getValue(); blueValue = blue.getValue(); showStatus("Red is: " + redValue + "; Green is: " + greenValue + "; Blue is: " + blueValue); c1 = new Color(redValue, greenValue, blueValue); setBackground(c1); } } //html code <title> Example3 </title> <applet code="Example3.class" width= 300 height=200></applet> output demonstration Decisions – if clause Along the way I will show some examples how to use buttons , Labels and text fields. Example4 : How to use an if statement import java.awt.*; import java.applet.Applet; import java.awt.event.*; public class Example4 extends Applet implements AdjustmentListener{ private Scrollbar tom, jerry; private int tomValue= 0, jerryValue = 0; public void init(){ Label toms = new Label("Tom"); add(toms); tom = new Scrollbar(Scrollbar.HORIZONTAL, 0,1,0,100); add(tom); tom.addAdjustmentListener(this); Label jerrys = new Label("Jerry:"); add(jerrys); jerry = new Scrollbar(Scrollbar.HORIZONTAL, 0,1,0,100); add(jerry); jerry.addAdjustmentListener(this); } public void paint(Graphics g){ g.drawString("Tom", 5, 70); g.fillRect(40,60,tomValue,10); g.drawString("Jerry", 5, 85); g.fillRect(40, 75, jerryValue, 10); if (tomValue > jerryValue) g.drawString("Tom is bigger", 50,50); else g.drawString("Jerry is bigger", 50,50); } public void adjustmentValueChanged(AdjustmentEvent event){ tomValue = tom.getValue(); jerryValue = jerry.getValue(); repaint(); } } HTML code to invoke the program <title> Example4 </title> <applet code="Example4.class" width= 300 height=200></applet> Output Using Buttons As with scrollbars, use of buttons is accomplished using methods on one of the Java libraries, the AWT (Abstract Window Toolkit) library. The are six steps to setting up a button: 1. State that the class implements ActionsListener. 2. Declare a button variable, giving it a name. 3. Create a new button, giving it a label. 4. Add the button to the window 5. Inform the button that this object will respond to button events, using addActionListener. 6. Provide a method called actionPerformed to be invoked when a button click event occurs. Example5 (How to use buttons) import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class Example5 extends Applet implements ActionListener{ private int diameter = 20; private Button little, large; public void init(){ little = new Button("Little"); add(little); little.addActionListener(this); large = new Button("Large"); add(large); large.addActionListener(this); } public void paint(Graphics g){ g.setColor(Color.blue); g.fillOval(25, 25, diameter, diameter); } public void actionPerformed(ActionEvent event){ if (event.getSource() == little) diameter = diameter - 10; if (event.getSource()== large) diameter = diameter + 10; repaint(); } } HTML code to invoke the program <title> Example5 </title> <applet code="Example5.class" width= 300 height=200></applet> Output Text fields Text fields are another graphical user interface component for inputting information from the user of a program. Example6 (How to use text fields) import java.applet.*; import java.awt.*; import java.awt.event.*; public class Example6 extends Applet implements ActionListener{ private Button ageB; private TextField ageField; private int age; public void init(){ ageField = new TextField(10); add(ageField); ageField.addActionListener(this); ageB = new Button("MyAge"); add(ageB); ageB.addActionListener(this); } public void actionPerformed(ActionEvent event){ if (event.getSource() == ageB) age = Integer.parseInt(ageField.getText()); repaint(); } public void paint(Graphics g){ setBackground(Color.orange); g.drawString("Age is " + age, 50, 50); if (age >= 18) g.drawString("You can vote", 50, 100); else g.drawString("You can not vote", 50,100); } } HTML code to invoke the program <title> Example6 </title> <applet code="Example6.class" width= 300 height=200></applet> output Repetition – while, for and do Part of the great power of computers arises from their ability to perform repetitions extremely quickly. In the language of programming repetition is called a loop. There are three ways in which the Java Programmer can instruct the computer to perform repetition: - while - for - do While loop Example7 (how to use while loop) import java.awt.*; import java.applet.Applet; public class Example7 extends Applet{ public void paint(Graphics g){ int counter, x =5; counter = 0; while (counter < 8){ setBackground(Color.blue); g.drawString("*", x, 20); x = x + 10; counter++; } } } HTML code to invoke the program <title> Example7 </title> <applet code="Example7.class" width= 300 height=200></applet> Output for loop In the for loop, many of the ingredients of the while loop are bundled up together in the statement itself. Example8 (how to use a for loop) import java.awt.*; import java.applet.Applet; public class Example8 extends Applet{ public void paint(Graphics g){ int n = 0; int x = 20; int y = 20; for (int i = 0; i < 8; i++){ setBackground(Color.cyan); g.drawLine(x, y, x + 100, y); y = y + 10; n++; } } } HTML code to invoke the program <title> Example8 </title> <applet code="Example8.class" width= 300 height=200></applet> output do…while loop If you use while or for, the test is done at the beginning of the loop. In the do loop, the decision is made at the end of the loop. Example9 import java.awt.*; import java.applet.Applet; public class Example9 extends Applet{ public void paint(Graphics g){ int countOfSquares = 0; int riceOnThisSquare = 1; int totalRice = 0; int y=20; do{ countOfSquares++; g.drawString("On Square" + countOfSquares + "are" riceOnThisSquare, 10,y); totalRice = totalRice + riceOnThisSquare; riceOnThisSquare = riceOnThisSquare * 2; y=y+20; } while (totalRice < 100); g.drawString("Number of squares needed is " + countOfSquares, 10, y + 10); } } html code to invoke Example9 class <title> Example8 </title> <applet code="Example8.class" width= 300 height=200></applet> Output Objects and Classes Object-oriented programming is about constructing programs from objects. An object is a combination of some data (variables) and some actions (methods). - In Object Programming Languages a class is the specification of for any number of objects that are the same. Once a class has been described, a particular object is constructed by creating an instance of the class. Example10 import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class Example10 AdjustmentListener{ extends Applet implements private Button grow, shrink, left,right, vertGrow,vertShrink; private Circle myCircle; private Scrollbar red; private Scrollbar green; ActionListener, private Scrollbar blue; private int redValue; private int greenValue; private int blueValue; private Color color; public void init(){ grow = new Button("Grow"); add(grow); grow.addActionListener(this); shrink = new Button("Shrink"); add(shrink); shrink.addActionListener(this); left = new Button("left"); add(left); left.addActionListener(this); right = new Button("right"); add(right); right.addActionListener(this); vertGrow = new Button("Vertical Grow"); add(vertGrow); vertGrow.addActionListener(this); vertShrink = new Button("Vertical Shrink"); add(vertShrink); vertShrink.addActionListener(this); Label l1, l2, l3; l1 = new Label("Red:"); l2 = new Label("Green:"); l3 = new Label("Blue:"); red = new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,1000); green = new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,1000); blue = new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,1000); add(l1); add(red); add(l2); add(green); add(l3); add(blue); red.addAdjustmentListener(this); green.addAdjustmentListener(this); blue.addAdjustmentListener(this); myCircle = new Circle(); } public void adjustmentValueChanged(AdjustmentEvent event){ redValue = red.getValue(); greenValue = green.getValue(); blueValue = blue.getValue(); color = new Color(redValue, greenValue,blueValue); showStatus("Red is: " + redValue + "; Green is:" + greenValue + "; Blue is: " + blueValue); repaint(); } public void actionPerformed(ActionEvent event){ if (event.getSource() == grow ) myCircle.grow(); if (event.getSource() == shrink) myCircle.shrink(); if (event.getSource() == left) myCircle.left(); if (event.getSource() == right) myCircle.right(); if (event.getSource() == vertGrow) myCircle.vertGrow(); if (event.getSource() == vertShrink) myCircle.vertShrink(); repaint(); } public void paint(Graphics g){ g.setColor(color); myCircle.display(g); } } class Circle{ private int height = 10; private int width = 10; private int xCoord = 20, yCoord = 50; private int red = 0; private int greeen = 0; private int blue = 0; private Color color; public void display(Graphics g){ g.fillOval(xCoord, yCoord,width, height); } public void left(){ xCoord = xCoord - 10; } public void right(){ xCoord = xCoord + 10; } public void grow(){ width = width + 10; height = height +10; } public void shrink(){ width = width - 10; height = height -10; } public void vertGrow(){ height = height + 10; } public void vertShrink(){ height = height - 10; } public void newColor(int red, int green,int blue){ color = new Color(red,green,blue); } } <html><head> <title> Web page Example10 </title> </head> <body> <applet code = "Example10.class" width=800 height=800 > </applet> </body></html> Sample output Questions NOTE: the answers of all the questions are in bold. Multiple choice 1. Java graphics are based on ______________. a. inches b.centemeters c. pixels d. millicentemeter 2. In java, the most significant technique for reducing complexity a program into isolated sections is called _________________. a. classes b. methods c.parameters d.arguments 3. The list of parameters that the invocation must supply is called ___________. a. actual parameter b. formal parameter c. class parameter d. none of the above 4. The list of names and types that the writer of the method decides on is called _____________. a. actual parameter b. formal parameter c. class parameter d. none of the above 5. An ______________ method is invoked by the system when the applet is run. a. an init( ) b. paint( ) c. repaint( ) d. none of the above True/False 1. We use a keyword private when a method can only be invoked from with in the current applet program. a.True b.False 2. We use a keyword public when a method can be invoked by another program. a. True b.False 3. An Applet is a completely free standing program. a.True b. False 4. Java application is invoked as part of a Web page and therefore needs either a Web browser to invoke it. a.True b.False 5. In programming languages, an event is always an action taken by the user. a.True b.False Fill in the blanks 1. To create a button on the screen, we must first specify that the class implements____________________. Answer: ActionListener 2. When a button is pressed, the method ____________________ is invoked by the Applet viewer or browser. Answer: actionPerformed 3. In Java Applet classes that handle events named _________________ and _____________. Answer. ActionListener and AdjustmentListener 4. In Java Applet an event class that handles scrollbars is called________________. Answer: AdjustmentListener. 5. In Java Applet an event class that handles buttons and textfields is called________________. Answer: ActionListener.