Applets and GUI Event Handling in JAVA
Applets and GUI Event Handling in JAVA
Applets and GUI Event Handling in JAVA
Handling in JAVA
import java.applet.Applet;
import java.awt.Graphics;
public class hello extends Applet {
public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25);
}
}
2
import is a keyword
java.applet is the name of the package
A dot ( . ) separates the package from
the class
Applet is the name of the class
There is a semicolon ( ; ) at the end
6
10
11
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class hello extends Applet {
String msg;
public void init(){
setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inside init()";
}
public void start()
{setForeground(Color.red);
msg+=" NOW in start";
}
public void paint(Graphics g) {setForeground(Color.red);
msg+=" NOW in paint";
g.drawString(msg, 50, 25);
}
}
12
13
14
16
Colors
The java.awt package defines a class named Color
There are 13 predefined colorshere are their
fully-qualified names:
Color.BLACK
Color.PINK
Color.GREEN
Color.DARK_GRAY Color.RED
Color.CYAN
Color.GRAY
Color.ORANGE
Color.BLUE
Color.LIGHT_GRAY Color.YELLOW
Color.WHITE
Color.MAGENTA
New colors
Every color is a mix of red, green,
and blue
You can make your own colors:
Color n= new Color( red , green ,
blue )
Amounts range from 0 to 255
Black is (0, 0, 0), white is (255, 255,
255)
We are mixing lights, not pigments
Yellow is red + green, or (255, 255,
19
Setting a color
To use a color, we tell our Graphics g
what color we want:
g.setColor(Color.RED);
20
21
Pixels
A pixel is a picture (pix) element
one pixel is one dot on your screen
there are typically 72 to 90 pixels per inch
22
(50, 0)
(0, 20)
(50, 20)
(w-1, h-1)
23
Drawing rectangles
There are two ways to draw rectangles:
g.drawRect( left , top , width , height );
24
25
Chess board
import java.applet.Applet;
import java.awt.*;
// CIT 591 example
public class Drawing extends Applet {
public void paint(Graphics g) {
int row, col;
int x,y;
for(row=0;row<8;row++)
{ for(col=0;col<8;col++)
{ x=col*20; y=row*20;
If( (row%2)==(col%2))
g.setColor(Color.RED);
else
g.setColor(Color.Black);
g.fillRect(x,y,20,20);
}}}}
26
g.drawLine( x1 , y1 , x2 , y2 );
g.drawOval( left , top , width , height );
g.fillOval( left , top , width , height );
g.drawRoundRect( left , top , width , height );
g.fillRoundRect( left , top , width , height );
g.drawArc( left , top , width , height ,
startAngle , arcAngle );
g.drawString( string , x , y );
27