Vous êtes sur la page 1sur 35

An applet program to draw circle in center of the canvas

/* <applet code="centerCircle" height=300 width=300>

</applet> */

import java.awt.*;
import java.applet.*;
publicclass centerCircle extends Applet
{
publicvoid paint(Graphics g){
Dimension d = getSize();
int x = d.width/2;
int y = d.height/2;
int radius = (int) ((d.width < d.height) ? 0.4 * d.width : 0.4 *
d.height);
g.setColor(Color.cyan);
g.fillOval(x-radius, y-radius, 2*radius, 2*radius);
g.setColor(Color.red);
g.drawString("Width
= "+d.width,10,10);
g.drawString("Height = "+d.height,10,20);
}
}

Code for An applet program to draw concentric circle in center of the canvas in
Java
/* <applet code="ConcentricCircle" height=500 width=500>

</applet> */

import java.awt.*;
import java.applet.*;
publicclass ConcentricCircle extends Applet
{
publicvoid paint(Graphics g){
Dimension d = getSize();
int x = d.width/2;
int y = d.height/2;
int r1 = (int) ((d.width < d.height) ? 0.4 * d.width : 0.4 * d.height);
g.setColor(Color.red);
g.fillOval(x-r1, y-r1, 2*r1, 2*r1);
int r2 = (int) ((d.width < d.height) ? 0.3 * d.width : 0.3 * d.height);
g.setColor(Color.blue);
g.fillOval(x-r2, y-r2, 2*r2, 2*r2);
int r3 = (int) ((d.width < d.height) ? 0.2 * d.width : 0.2 * d.height);
g.setColor(Color.yellow);
g.fillOval(x-r3, y-r3, 2*r3, 2*r3);
int r4 = (int) ((d.width < d.height) ? 0.1 * d.width : 0.1 * d.height);
g.setColor(Color.green);
g.fillOval(x-r4, y-r4, 2*r4, 2*r4);
g.setColor(Color.red);
g.drawString("Width
= "+d.width,10,10);
g.drawString("Height = "+d.height,10,20);
}

**********************************************************************************

How to properly create an applet with an


Input field and some shapes
import
import
import
import

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

public class Alpha extends JApplet implements ActionListener


{
private JLabel inputLabel;
private JButton doIt;
private JTextField numVariable;
private String numAsString;
private JPanel myPanel;
private int num;
public void init()
{
setBackground(Color.lightGray);
inputLabel = new JLabel("Enter number:");
playVariable = new JTextField(4);
doIt = new JButton("Do it!");
doIt.addActionListener(this);
myPanelClass myPanel = new myPanelClass();
myPanel.add(inputLabel);
myPanel.add(numVariable);
myPanel.add(doIt);
getContentPane().add(myPanel);
}
public class myPanelClass extends JPanel
{
public void paintComponent(Graphics page) {
super.paintComponent(page);
if (num <= 0) return;
if (num == 1) {
page.setColor(Color.blue);
page.fillOval(50, 50, 20, 20);
} else if (num == 2) {
page.setColor(Color.green);

page.fillRect(50, 50, 40, 20);


} else if (num == 3) {
page.setColor(Color.gray);
page.drawLine(50,50,120,50);
}

public void actionPerformed(ActionEvent event) {


numAsString = numVariable.getText();
if (numAsString.length() <= 0) return;
num = Integer.parseInt(numAsString);
repaint();
}

******************************************************************************

Draw Oval & Circle in Applet Window Example


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.

/*
Draw Oval & Circle in Applet Window Example
This java example shows how to draw ovals & circles in an applet window using
drawOval method of Graphics class. It also shows how to draw a filled
ovals and circles using fillOval method of Graphics class.
*/
/*
<applet code="DrawOvalsExample" width=500 height=500>
</applet>
*/
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class DrawOvalsExample extends Applet{
public void paint(Graphics g){
//set color to red
setForeground(Color.red);
/*
* to draw a oval in an applet window use,
* void drawOval(int x1,int y1, int width, int height)
* method.
*
* This method draws a oval of specified width and
* height at (x1,y1)
*/
//this will draw a oval of width 50 & height 100 at (10,10)
g.drawOval(10,10,50,100);
/*
* To draw a filled oval use

40.
41.
42.
43.
44.
45.
46.
47.
48.

* fillOval(int x1,int y1, int width, int height)


* method of Graphics class.
*/
//draw filled oval
g.fillOval(100,20,50,100);
}
}

**********************************************************************************

Drawing Circles (Graphics with Applets)


By S. Nageswara Rao, Corporate Trainer on May 8, 2011

No special or predefined method exists with Graphics class to draw circles. But still,
circles can be drawn in three styles using other methods.

1. Using drawRoundRect()
2. Using drawOval() most preferred
3. Using drawArc()

All the earlier programs like drawing rectangles are illustrated with Frame. Now let
us go for applet. Applet includes init(), start() and paint() methods etc.
The migration steps from graphics application to applet are available in "Java
AWT Radio Buttons Applet GUI".
Knowledge of "applets" is required to do with this program.
Applet File Name: ThreeStyles.java
1
2
3
4
5
6
7
8
9

import java.awt.Graphics;
import java.applet.Applet;
public class ThreeStyles extends Applet
{
public void paint (Graphics g)
{
// using drawRoundRect()
g.drawRoundRect(40, 50, 90, 90, 200, 200);
g.fillRoundRect(40, 160, 90, 90, 200, 200);
// using drawOval()
g.drawOval(150, 50, 90, 90);

10
11
g.fillOval(150, 160, 90, 90);
12
// using drawArc()
13
g.drawArc(270, 50, 90, 90, 0, 360);
14
g.fillArc(270, 160, 90, 90, 0, 360);
15 }
16 }

***************************************************************************
*

Drawing Shapes and using colors


/*
Applet will paint special shapes and use colors and fonts
Only new methods are explained
*/
import java.awt.*;
import java.applet.*;
public class DrawExample extends Applet
{
// Specify variables that will be needed everywhere, anytime here
// The font variable
Font bigFont;
// The colors you will use
Color redColor;
Color weirdColor;
Color bgColor;
public void init()
{
// Here we will define the varibles further
// Will use Arial as type, 16 as size and bold as style
// Italic and Plain are also available
bigFont = new Font("Arial",Font.BOLD,16);
// Standard colors can be named like this
redColor = Color.red;
// lesser known colors can be made with R(ed)G(reen)B(lue).
weirdColor = new Color(60,60,122);
bgColor = Color.blue;
// this will set the backgroundcolor of the applet
setBackground(bgColor);

}
public void stop()
{
}
// now lets draw things on screen
public void paint(Graphics g)
{
// tell g to use your font
g.setFont(bigFont);
g.drawString("Shapes and Colors",80,20);
// Now we tell g to change the color
g.setColor(redColor);
// This will draw a rectangle (xco,yco,xwidth,height);
g.drawRect(100,100,100,100);
// This will fill a rectangle
g.fillRect(110,110,80,80);
// change colors again
g.setColor(weirdColor);
// a circle (int x, int y, int width, int height,int startAngle, int arcAngle);
// ovals are also possible this way.
g.fillArc(120,120,60,60,0,360);
g.setColor(Color.yellow);
// Draw a line (int x1, int y1, int x2, int y2)
g.drawLine(140,140,160,160);
// reset the color to the standard color for the next time the applets
paints
// an applet is repainted when a part was'nt visible anymore
// happens most often because of browser minimizing or scrolling.
g.setColor(Color.black);
}
}

// that's some basic drawing.


// next is drawing images on screen
// go to imageExample.java

Creating Multiplication Table in Java


A multiplication table is a table of numbers which lists product of a decimal sequence
of numbers. For example, a multiplication table of 9 by 9 contains a top most row
with values ranging from 1 to 9 and a left most row with values ranging from 1 to 9.
The middle cells contains the algebraic product of the corresponding value in the top
row and left most row. Following is a 5 by 5 multiplication table,

10

12

15

12

16

20

10

15

20

25

Using a multiplication table it is easy to find product of two numbers. For example, to
find the product of 4 and 5, we just need to look at the cell located on the 4th row
and 5th column which returns the result as 20.
It is important to memorize multiplication tables as it the foundation of mathematical
calculations. Children are usually taught to memorize multiplication tables up to 9 by
9. This enables children to do multiply large numbers without the need of a
calculator.
The technique of memorizing the table was to take one column at a time and then
memorize it. For example, the multiplication table for number 7 is memorized as,

1x7

2x7

14

3x7

21

4x7

28

5x7

35

6x7

42

7x7

49

8x7

56

9x7

63

10 x 7

70

Java Program to Print a 9 by 9 Multiplication Table


The following Java program generates the entire multiplication table for values from
1 to 9. This is printed in a formatted table. We use nested loops to generate the
multiplication table. Also note the use of System.out.format() method to format the
table. The format string %4d instructs the formatter to print the integer in 4
character width padding with spaces as necessary.
1

/* Prints multiplication table in Java */

public class FullMultiplicationTable {

3
4

public static void main(String[] args) {

int tableSize = 9;

printMultiplicationTable(tableSize);

8
9
10

public static void printMultiplicationTable(int tableSize) {


// first print the top header row

11

System.out.format("

");

12

for(int i = 1; i<=tableSize;i++ ) {

13

System.out.format("%4d",i);

14

15
16

System.out.println();
System.out.println("------------------------------------------")
;

17
18

for(int i = 1 ;i<=tableSize;i++) {

19

// print left most column first

20

System.out.format("%4d |",i);

21

for(int j=1;j<=tableSize;j++) {

22

System.out.format("%4d",i*j);

23

24

System.out.println();

25
26

}
}

27
28

The output generated by the multiplication table program in java is given below,

Java Program to Print Multiplication Table for an Integer


The following program generates multiplication table for an integer. The table
contains product values for the integer when it is multiplied with values ranging from
1 to 10. This form is usually used to memorize the multiplication table,
1 /* Generates multiplication table for an integer */

2 public class MultiplicationTable {


3
4

public static void main(String[] args) {

int number = 7;

6
7
8

printMultiplicationTable(number);
}

9
10

private static void printMultiplicationTable(int n) {

11

System.out.println("Multiplication table for "+n);

12

System.out.println("---------------------------");

13

for(int i = 1; i<=10;i++) {

14

System.out.format("%2d x %d = %3d\n", i,n,i*n);

15
16

}
}

17
18

The formatted multiplication table output is given below,

********************************************************************************

Java applet program for interest rate calculation


Write a Java program that computes the payment of a loan based on the amount of
the loan, the interest rate and the number of months. It takes one parameter from
the browser: Monthly rate;if true, the interest rate is per month; Otherwise the
interest rate is annual.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Loan" width=300 height=300>
</applet>
*/
public class Loan extends Applet
implements ActionListener,ItemListener
{
double p,r,n,total,i;
String param1;
boolean month;
Label l1,l2,l3,l4;
TextField t1,t2,t3,t4;
Button b1,b2;
CheckboxGroup cbg;
Checkbox c1,c2;
String str;
public void init()
{
l1=new Label("Balance Amount",Label.LEFT);
l2=new Label("Number of Months",Label.LEFT);
l3=new Label("Interest Rate",Label.LEFT);
l4=new Label("Total Payment",Label.LEFT);
t1=new TextField(5);
t2=new TextField(5);
t3=new TextField(15);
t4=new TextField(20);
b1=new Button("OK");
b2=new Button("Delete");
cbg=new CheckboxGroup();
c1=new Checkbox("Month Rate",cbg,true);
c2=new Checkbox("Annual Rate",cbg,true);
t1.addActionListener(this);
t2.addActionListener(this);
t3.addActionListener(this);
t4.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
c1.addItemListener(this);
c2.addItemListener(this);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);

49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83 }

Output:

add(l4);
add(t4);
add(c1);
add(c2);
add(b1);
add(b2);

}
public void itemStateChanged(ItemEvent ie)
{
}
public void actionPerformed(ActionEvent ae)
{
str=ae.getActionCommand();
if(str.equals("OK"))
{
p=Double.parseDouble(t1.getText());
n=Double.parseDouble(t2.getText());
r=Double.parseDouble(t3.getText());
if(c2.getState())
{
n=n/12;
}
i=(p*n*r)/100;
total=p+i;
t4.setText(" "+total);
}
else if(str.equals("Delete"))
{
t1.setText(" ");
t2.setText(" ");
t3.setText(" ");
t4.setText(" ");
}
}

Java applet program output for interest rate


calculation

Simple Interest Calculator Java


Applet
POSTED BY ADMIN AT 1:20 PM 0 COMMENTS

A sample interest calculator, very basic in functionality, coded in Java and ready to be compiled and executed as
a Java Applet.

view plainprint?

1.

import java.awt.*;

2.

import java.awt.event.*;

3.

import java.applet.*;

4.

import java.text.NumberFormat;

5.
6.

public class InterestCalculator extends Applet implements ActionListener

7.
8.

TextField textPresentVal = new TextField("0", 10);

9.

TextField textInterestRate = new TextField("0", 10);

10.

TextField textPeriods = new TextField("0", 10);

11.

Label lblPresentVal = new Label("Present Value");

12.

Label lblInterestRate = new Label("Interest Rate");

13.

Label lblPeriods = new Label("Number of Periods");

14.

Label lblFutureVal = new Label("Future Value:");

15.

Button btnOk = new Button("Calculate");

16.
17.

public void init()

18.

19.
20.

add(lblPresentVal);

21.

add(textPresentVal);

22.

add(lblInterestRate);

23.

add(textInterestRate);

24.

add(lblPeriods);

25.

add(textPeriods);

26.

add(lblFutureVal);

27.

add(btnOk);

28.
29.
30.

btnOk.addActionListener(this);
}

31.
32.

public void actionPerformed(ActionEvent evt)

33.

34.

if (evt.getSource() == btnOk)

35.

36.

int PresentVal = Integer.parseInt(textPresentVal.getText());

37.

int InterestRate = Integer.parseInt(textInterestRate.getText());

38.

int Periods = Integer.parseInt(textPeriods.getText());

39.

double FutureVal = PresentVal * (Math.pow((1 + InterestRate), Periods));

40.

NumberFormat nf = NumberFormat.getCurrencyInstance();

41.

lblTotal.setText("Future Value: " + nf.format(FutureVal));

42.
43.

repaint();

44.

45.
46.

}
}

On Friday, July 31st


2009 at 08:30 PM

Simple Interest Calculator Java


Applet

By Andrew Pociu (View Profile)

A sample interest calculator, very basic in functionality, coded


in Java and ready to be compiled and executed as a Java
(Rated 4.1 with 11

Applet.

votes)

Contextual Ads
More Java Resources
Java Tutorials
Java Code
Java Jobs
Advertisement

1. import java.awt.*;
2. import java.awt.event.*;

3. import java.applet.*;
4. import java.text.NumberFormat;
5.
6. public class InterestCalculator extends Applet implementsActionListener
7. {
8.

TextField textPresentVal = new TextField("0", 10);

9.

TextField textInterestRate = new TextField("0", 10);

10.

TextField textPeriods = new TextField("0", 10);

11.

Label lblPresentVal = new Label("Present Value");

12.

Label lblInterestRate = new Label("Interest Rate");

13.

Label lblPeriods = new Label("Number of Periods");

14.

Label lblFutureVal = new Label("Future Value:");

15.

Button btnOk = new Button("Calculate");

16.
17.

public void init()

18.

19.
20.

add(lblPresentVal);

21.

add(textPresentVal);

22.

add(lblInterestRate);

23.

add(textInterestRate);

24.

add(lblPeriods);

25.

add(textPeriods);

26.

add(lblFutureVal);

27.

add(btnOk);

28.
29.
30.

btnOk.addActionListener(this);
}

31.
32.

public void actionPerformed(ActionEvent evt)

33.

34.

if (evt.getSource() == btnOk)

35.

36.

int PresentVal
= Integer.parseInt(textPresentVal.getText());

37.

int InterestRate
= Integer.parseInt(textInterestRate.getText());

38.

int Periods = Integer.parseInt(textPeriods.getText());

39.

double FutureVal = PresentVal * (Math.pow((1 +


InterestRate), Periods));

40.

NumberFormat nf = NumberFormat.getCurrencyInstance();

41.

lblTotal.setText("Future Value: " +


nf.format(FutureVal));

42.
43.
44.

repaint();
}

45.

46. }

********************************************************************************

Create Number counter in an Applet using Thread Example


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.

/*

Create Number counter in an Applet using Thread Example


This Java example shows how to create number counter using Java Thread and
Applet classes.

*/
import
import
import
import
import

java.applet.Applet;
java.awt.Dimension;
java.awt.Font;
java.awt.FontMetrics;
java.awt.Graphics;

/*
<applet code = "UsingRepaintAndThreadExample" width = 500 height = 300>
</applet>
*/
/*

Using paint() method we can draw strings, shapes or images.


But when applets that use threads commonly need to update the display
(ex. Animation or simulation).
You cannot invoke the paint method directly to update the display.
The reason is that the JVM schedules a number of important tasks. Updating
the dispaly is one of these. The JVM decides when the screen can be updated.
Therefore, your applet must invoke the repaint() method to request
an update of the applet display. When the JVM determines that it is
appropriate to perform this work, it calls the update method.

*/

The default implementation of the update() method clears the applet


display with the background color and then invokes the paint() method.

public class UsingRepaintAndThreadExample extends Applet implements Runnable{


int counter;
Thread t;
public void init(){
counter = 0;
t = new Thread(this);

44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.

t.start();

public void run(){


try{
while(true){
repaint();
Thread.sleep(1000);
++counter;
}

}
catch(Exception e){
}

public void paint(Graphics g){


g.setFont(new Font("Serif",Font.BOLD,30));
FontMetrics fm = g.getFontMetrics();
String s = "" + counter;
Dimension d = getSize();
int x = d.width/2 - fm.stringWidth(s)/2;
int y = d.height/2;
g.drawString(s,x,y);
}

Draw 3D Rectangle & Square in Applet Window Example


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.

/*
Draw 3D Rectangle & Square in Applet Window Example
This java example shows how to draw 3-D rectangles and squares in an applet
window using draw3DRect method of Graphics class. It also shows how to
draw a filled 3-D rectangles and squares.
*/
/*
<applet code="Draw3DRectanglesExample" width=200 height=200>
</applet>
*/
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class Draw3DRectanglesExample extends Applet{
public void paint(Graphics g){
g.setColor(Color.green);
/*

24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.

* To draw a 3-D rectangle in an applet window use,


* void draw3DRect(int x1,int y1, int width, int height, boolean raised)
* method.
*
* This method draws a 3-D rectangle of specified width and
* height at (x1,y1)
*/
//this will draw a 3-D rectangle of width 50 & height 100 at (10,10)
g.draw3DRect(10,10,50,100,true);
/*
* If you speficy same width and height, the draw3DRect method
* will draw a 3-D square!
*/
//this will draw a 3-D square
g.draw3DRect(100,100,50,50,true);
g.setColor(Color.orange);
/*
* To draw a filled 3-D rectangle in an applet window use,
* void fill3DRect(int x1,int y1, int width, int height, boolean raised)
* method.
*
* This method draws a filled 3-D rectangle of specified width and
* height at (x1,y1)
*/
//this will draw a filled 3-D rectangle of width 50 & height 100 at (10,10)
g.fill3DRect(10,150,50,100,true);
/*
* If you speficy same width and height, the fill3DRect method
* will draw a filled 3-D square!
*/
//this will draw a filled 3-D square
g.fill3DRect(100,200,50,50,true);
}
}

Draw Arc in Applet Window Example


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.

/*

*/

Draw Arc in Applet Window Example


This java example shows how to draw arc in an applet window using
drawArc method of Graphics class. It also shows how to draw a filled
arcs using fillArc method of Graphics class.

/*
<applet code="DrawOvalsExample" width=500 height=500>
</applet>
*/

13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class DrawArcExample extends Applet{
public void paint(Graphics g){
//set color to red
setForeground(Color.red);
/*
* to draw an arc in an applet window use,
* void drawArc(int x1,int y1, int width, int height,int startAngle, int arcAngle)
* method.
*
* This method draws an arc of specified width and
* height at (x1,y1)
*/
//this will draw an arc of width 50 & height 100 at (10,10)
g.drawArc(10,10,50,100,10,45);
/*
* To draw a filled arc use
* fillArc(int x1,int y1, int width, int height,int startAngle, int arcAngle)
* method of Graphics class.
*/
//draw filled arc
g.fillArc(100,10,100,100,0,90);
}

Draw Dots at Random Locations in an Applet Example


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.

/*

*/

Draw Dots at Random Locations in an Applet Example


This Java example shows draw dots at random locations at specified interval
using Java Thread and Applet classes.

import java.applet.Applet;
import java.awt.Dimension;
import java.awt.Graphics;
/*
<applet code = "DrawDotsAtRandomLocationsExample" width = 500 height = 300>
</applet>
*/
public class DrawDotsAtRandomLocationsExample extends Applet implementsRunnable
Thread t;

17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.

public void init(){


//start new Thread
t = new Thread(this);
t.start();
}
public void run(){
try{
while(true){
// Request repaint
repaint();
Thread.sleep(200);
}
}
catch(Exception e){
}
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
Dimension d = getSize();
int x = (int)(Math.random() * d.width);
int y = (int)(Math.random() * d.height);
g.fillRect(x,y,2,2);
}

Fill Rectangle & Square in Applet Window Example


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.

/*

*/

Fill Rectangle & Square in Applet Window Example


This java example shows how to draw filled rectangles and squares in an
applet window using fillRect method of Graphics class.

/*
<applet code="FilledRectangleExample" width=200 height=200>
</applet>
*/
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class FilledRectangleExample extends Applet{
public void paint(Graphics g){

20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.

//set color to red


setForeground(Color.red);
/*
* to draw a filled rectangle in an applet window use,
* void fillRect(int x1,int y1, int width, int height)
* method.
*
* This method draws a filled rectangle of specified width and
* height at (x1,y1)
*/
//this will draw a filled rectangle of width 50 & height 100 at (10,10)
g.fillRect(10,10,50,100);
/*
* If you speficy same width and height, the fillRect method
* will draw a filled square!
*/

//this will draw a filled square


g.fillRect(100,100,50,50);

Draw Oval & Circle in Applet Window Example


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.

/*
Draw Oval & Circle in Applet Window Example
This java example shows how to draw ovals & circles in an applet window using
drawOval method of Graphics class. It also shows how to draw a filled
ovals and circles using fillOval method of Graphics class.
*/
/*
<applet code="DrawOvalsExample" width=500 height=500>
</applet>
*/
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class DrawOvalsExample extends Applet{
public void paint(Graphics g){
//set color to red
setForeground(Color.red);
/*
* to draw a oval in an applet window use,
* void drawOval(int x1,int y1, int width, int height)

28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.

* method.
*
* This method draws a oval of specified width and
* height at (x1,y1)
*/
//this will draw a oval of width 50 & height 100 at (10,10)
g.drawOval(10,10,50,100);
/*
* To draw a filled oval use
* fillOval(int x1,int y1, int width, int height)
* method of Graphics class.
*/
//draw filled oval
g.fillOval(100,20,50,100);
}
}

Draw Rounded Corner Rectangle & Square in Applet Window


Example
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.

/*

*/

Draw Rounded Corner Rectangle & Square in Applet Window Example


This java example shows how to draw rounded corner rectangles and squares
in an applet window using drawRoundRect method of Graphics class. It also
shows how to draw a filled rounded corner rectangles and squares using
fillRoundRect method of Graphics class.

/*
<applet code="DrawRoundedRectExample" width=500 height=500>
</applet>
*/
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class DrawRoundedRectExample extends Applet{
public void paint(Graphics g){
//set color to red
setForeground(Color.red);

arcHeight)

/*
* to draw a rounded corner rectangle in an applet window use,
* void drawRoundRect(int x1,int y1, int width, int height, int arcWidth, int
* method.
*
* This method draws a rounded corner rectangle of specified width and

32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.

* height at (x1,y1)
*/
//this will draw a round cornered rectangle of width 50 & height 100 at (10,10)
g.drawRoundRect(10,10,50,100,10,10);
/*
* If you speficy same width and height, the drawRoundRect method
* will draw a round cornered square!
*/
//this will draw a round cornered square
g.drawRoundRect(100,100,50,50,10,10);
/*
* To draw a filled round cornered rectangle or square use
* fillRoundRect(int x1,int y1, int width, int height, int arcWidht, int arcHeight)
* method of Graphics class.
*/
//set color to blue
//setForeground(Color.blue);
//draw filled rounded corner rectangle
g.fillRoundRect(200,20,50,100,10,10);
//draw filled square
g.fillRoundRect(200,200,50,50,10,10);
}

Draw Smiley In Applet Example


Submitted By: Sagar
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.

/*

Draw Smiley In Applet Example


This Java example shows how to to draw smiley in an applet window using
drawString Java Applet class.

*/
import java.awt.*;
import java.applet.*;
public class Smiley extends Applet{
public void paint(Graphics g){
Font f = new Font("Helvetica", Font.BOLD,20);
g.setFont(f);
g.drawString("Keep Smiling!!!", 50, 30);
g.drawOval(60, 60, 200, 200);
g.fillOval(90, 120, 50, 20);
g.fillOval(190, 120, 50, 20);
g.drawLine(165, 125, 165, 175);
g.drawArc(110, 130, 95, 95, 0, -180);
}

24.

Fill Rectangle & Square in Applet Window Example


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.

/*

Fill Rectangle & Square in Applet Window Example


This java example shows how to draw filled rectangles and squares in an
applet window using fillRect method of Graphics class.

*/
/*
<applet code="FilledRectangleExample" width=200 height=200>
</applet>
*/
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class FilledRectangleExample extends Applet{
public void paint(Graphics g){
//set color to red
setForeground(Color.red);
/*
* to draw a filled rectangle in an applet window use,
* void fillRect(int x1,int y1, int width, int height)
* method.
*
* This method draws a filled rectangle of specified width and
* height at (x1,y1)
*/
//this will draw a filled rectangle of width 50 & height 100 at (10,10)
g.fillRect(10,10,50,100);
/*
* If you speficy same width and height, the fillRect method
* will draw a filled square!
*/
//this will draw a filled square
g.fillRect(100,100,50,50);
}
}

Java Examples - Create different


shapes in an Applet
Advertisements

Previous Page
Next Page

Problem Description:
How to create different shapes using Applet?

Solution:
Following example demonstrates how to create an applet which will have a line, an Oval & a
Rectangle using drawLine(), drawOval(, drawRect() methods of Graphics clas.
import java.applet.*;
import java.awt.*;

public class Shapes extends Applet{


int x=300,y=100,r=50;
public void paint(Graphics g){
g.drawLine(30,300,200,10);
g.drawOval(x-r,y-r,100,100);
g.drawRect(400,50,200,100);
}
}

Result:
The above code sample will produce the following result in a java enabled web browser.
A line , Oval & a Rectangle will be drawn in the browser.

ava Examples - Fill colors using Applet?


Advertisements

Previous Page
Next Page

Problem Description:
How to fill colors in shapes using Applet?

Solution:
Following example demonstrates how to create an applet which will have fill color in a rectangle
using setColor(), fillRect() methods of Graphics class to fill color in a Rectangle.
import java.applet.*;
import java.awt.*;

public class fillColor extends Applet{


public void paint(Graphics g){
g.drawRect(300,150,200,100);
g.setColor(Color.yellow);
g.fillRect( 300,150, 200, 100 );
g.setColor(Color.magenta);
g.drawString("Rectangle",500,150);
}
}

Result:
The above code sample will produce the following result in a java enabled web browser.
A Rectangle with yellow color filled in it willl be drawn in the browser.

Java Examples - display a clock using


Applet?
Advertisements

Previous Page
Next Page

Problem Description:
How to display clock using Applet?

Solution:
Following example demonstrates how to display a clock using valueOf() mehtods of String
Class. & using Calender class to get the second, minutes & hours.
import java.awt.*;
import java.applet.*;

import java.applet.*;
import java.awt.*;
import java.util.*;

public class ClockApplet extends Applet implements Runnable{


Thread t,t1;
public void start(){
t = new Thread(this);
t.start();
}
public void run(){

t1 = Thread.currentThread();
while(t1 == t){
repaint();
try{
t1.sleep(1000);
}
catch(InterruptedException e){}
}
}
public void paint(Graphics g){
Calendar cal = new GregorianCalendar();
String hour = String.valueOf(cal.get(Calendar.HOUR));
String minute = String.valueOf(cal.get(Calendar.MINUTE));
String second = String.valueOf(cal.get(Calendar.SECOND));
g.drawString(hour + ":" + minute + ":" + second, 20, 30);
}
}

Result:
The above code sample will produce the following result in a java enabled web browser.
View in Browser.

*********************************************************************************

Code for An applet program that displays Text at the center of the
string which is passed as parameter in Java
import java.awt.*;
import java.applet.*;
publicclass displayCenter extends Applet
{
String str;
publicvoid paint(Graphics g)
{
str="Centering Text";
Font f = new Font("Serif", Font.BOLD, 30);
g.setFont(f);
FontMetrics fm = g.getFontMetrics();
Dimension d = getSize();

int xc,yc;
xc=d.width/2 - fm.stringWidth(str)/2;
yc=d.height/2 + fm.getDescent();
g.setColor(Color.red);
g.drawString(str,xc,yc);
showStatus(" Displaying Text at Center of Screen");
}
}

********************************************************************************

Write an applet to draw concentric circles in different colors

import java.applet.*;
import java.awt.*;
/*<applet code="ConcCircles" height=250 width=300>
</applet>
*/
/*
A Special Note:
While specifying an oval we have to pass the top-left corner (x,y) co-ordinates of
the bounding box and the height and width of the bounding box
A bounding box is defined as the smallest rectangle which can completely contain
the oval
If the height and width is same then a circle is drawn
*/
public class ConcCircles extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.RED);
g.drawOval(50,50,150,150);
above for explanation of parameters
g.setColor(Color.BLUE);
blue
g.drawOval(75,75,100,100);
circle is drawn
g.setColor(Color.GREEN);
g.drawOval(100,100,50,50);
}
}

//Set the colour to red


// Refer to special note
// Set the colour to
// 100 pixel diameter
//Set the colour to green

/* To compile type (in command line): javac ConcCircles.java


To run type (in command line): appletviewer ConcCircles.java
*/

Java Program to Find Area of Square,Rectangle and Circle


using Method Overloading

This is a Java Program to Find Area of Square, Rectangle and Circle using Method Overloading.

We declare three methods of same name but with different number of arguments or with
different data types. Now when we call these methods using objects, corresponding
methods will be called as per the number of arguments or their datatypes.
Here is the source code of the Java Program to Find Area of Square, Rectangle and
Circle using Method Overloading. The Java program is successfully compiled and run on
a Windows system. The program output is also shown below.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.

class OverloadDemo
{
void area(float x)
{
System.out.println("the area of the square is "+Math.pow(x, 2)+" sq units");
}
void area(float x, float y)
{
System.out.println("the area of the rectangle is "+x*y+" sq units");
}
void area(double x)
{
double z = 3.14 * x * x;
System.out.println("the area of the circle is "+z+" sq units");
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
ob.area(5);
ob.area(11,12);
ob.area(2.5);
}
}

Output:
$ javac OverloadDemo.java
$ java OverloadDemo
the area of the square is 25.0 sq units
the area of the rectangle is 132.0 sq units
the area of the circle is 19.625 sq units

**********************************************************************************

3) Write a java program which creates class Student


(Roll no, Name,- Number of subjects, Marks of each
subject)(Number of subjects varies for each student)
Write a parameterized constructor which initializes
roll no, name & Number of subjects and create the
array of marks dynamically. Display the details of all
students with percentage and class obtained.
import java.io.*;
class Student
{
int rollno;
String name;
int number_of_subjects;
int mark[];
Student(int roll,String stud_name,int noofsub)throws IOException
{
rollno=roll;
name=stud_name;
number_of_subjects= noofsub;
getMarks(noofsub);
}
public void getMarks(int nosub ) throws IOException
{
mark=new int[nosub];
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
for (int i=0; i<nosub;i++)
{
System.out.println(Enter +i+Subject Marks.:=> );
mark[i]=Integer.parseInt(br.readLine());
System.out.println();
}
}
public void calculateMarks()
{
double percentage=0;

String grade;
int tmarks=0;
for (int i=0;i<mark.length;i++)
{
tmarks+=mark[i];
}
percentage=tmarks/number_of_subjects;
System.out.println(Roll Number :=> +rollno);
System.out.println(Name Of Student is :=> +name);
System.out.println(Number Of Subject :=> +number_of_subjects);
System.out.println(Percentage Is :=> +percentage);
if (percentage>=70)
System.out.println(Grade Is First Class With Distinction );
else if(percentage>=60 && percentage<70)
System.out.println(Grade Is First Class);
else if(percentage>=50 && percentage<60)
System.out.println(Grade Is Second Class);
else if(percentage>=40 && percentage<50)
System.out.println(Grade Is Pass Class);
else
System.out.println(You Are Fail);
}
}
class StudentDemo
{
public static void main(String args[])throws IOException
{
int rno,no,nostud;
String name;
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
System.out.println(Enter How many Students:=> );
nostud=Integer.parseInt(br.readLine());
Student s[]=new Student[nostud];
for(int i=0;i<nostud;i++)
{
System.out.println(Enter Roll Number:=> );
rno=Integer.parseInt(br.readLine());
System.out.println(Enter Name:=> );
name=br.readLine();
System.out.println(Enter No of Subject:=> );
no=Integer.parseInt(br.readLine());
s[i]=new Student(rno,name,no);

}
for(int i=0;i<nostud;i++)
{
s[i].calculateMarks();
}
}
}

Vous aimerez peut-être aussi