Latest News

New Summer Look :)










Applets, AWT, Graphics and Layouts

  (3) AWT Graphics

The Graphics Class

Painting Into Graphics

Painting Into Graphics Example

Fonts

Fonts Example

(4) Layout Managers

Five Ready Layout Policies

Applets Basics

HTML Containing Applets

Applet : Important Methods

Applet : A First Example

A Scribble Application Example

Passing Values From HTML

Security Constrictions for Applets

Placing an Applet in an Application

Quiz

Exercises
 

 

(3) AWT Graphics

Numerous methods to draw lines, rectangles, circles, polygons, and images

Classes :

- Graphics

- Font, FontMetrics

- Color, SystemColor

- Dimension, Point

- MediaTracker

- java.awt.image.*


The Graphics Class

- Abstract Class used to draw on the screen and display images

- Protected Constructor

- Graphics is available to all the components on which the user may need to draw.

- These components need to implement :

public void paint(Graphics g)
update(Graphics g)

Painting Into Graphics

Most commonly used methods :

drawLine(x1, y1, x2, y2)

drawOval(x, y, width, height)

drawRect(x, y, width, height)

drawString(str, x, y)

setColor(Color)

setFont(Font)

fillRect(x, y, width, height)

draw3DRect(x, y, width, height, raised)

drawRoundRect(x, y, w, h, arcWidth, arcHeight)

 

Painting Into Graphics Example

 

import java.awt.*;

public class ShapesApplication extends Frame {
   static final String message = "Shapes!";
   private Font myFont;

   ShapesApplication(String str) {
     super(str);
     myFont = new Font("Helvetica", Font.BOLD, 36);
   }
   public static void main(String[] argv) {
    	ShapesApplication sa = 
                 new ShapesApplication("Shapes Example");
    	sa.setSize(400,300);
	sa.show();
   }
public void paint(Graphics g) {
   g.setColor(Color.black);
   g.setFont(myFont); // set Helvetica font
   g.setColor(Color.black);
   g.drawString(message, 150, 130); // draw the text      
   g.drawRect(10, 50, 80, 50); // draw two rectangles
   g.fillRect(10, 130, 80, 130);
   g.drawLine(100, 50, 180, 100); // draw one line
   int[] xPoints = {100, 120, 135, 160, 130};
   int[] yPoints = {70, 100, 160, 180,  100};
   g.drawPolyline(xPoints, yPoints, 5); 
   g.drawRoundRect(200, 50, 70, 50, 30, 30); 
   g.fillRoundRect(280, 50, 100, 50, 30, 30);     
   g.drawOval(200, 130, 50, 80); // draw 2 ovals    
   g.fillOval(270, 130, 100, 100); // draw 2 arcs
   g.drawArc(100, 200, 50, 70, 100, 100); 
   g.fillArc(150, 200, 80, 100, 130, 130);
  }  
  public boolean handleEvent(Event e) {
    if (e.id == Event.WINDOW_DESTROY) {
	dispose();
	System.exit(0);
	return true;
    }
    return super.handleEvent(e);
  }	    
} // end class
      

Fonts

- Represented in Java with the java.awt.Font class

- Small number of fonts, to promote platform independence

- Create a font by specifying a font family name, a font style and a point size

- Use setFont() on your Graphics object before calling drawString()


Fonts Example

 


 
import java.awt.*;
public class FontViewer extends Frame {
	public FontViewer(String s) {
	  super(s);
	}

// Available font names
String[] fontNames = {"Serif", "SansSerif",
         "Monospaced", "Dialog", "DialogInput"};

// Available styles names
String[] styleNames = {"Plain", "Italic", "Bold", "Bold Italic"};
int[] styles = {Font.PLAIN, Font.ITALIC, Font.BOLD,
                Font.ITALIC + Font.BOLD};
public void paint(Graphics g) {
 for (int fontNumber=0;fontNumber<fontNumber.length; fontNumber++) {
   for (int styleNumber=0; styleNumber < styles.length; styleNumber++) {
            Font f = new Font(fontNames[fontNumber],styles[styleNumber], 16);
	      String s = fontNames[fontNumber] + " " + styleNames[styleNumber];
	      g.setFont(f);
	      g.drawString(s, 10, (fontNumber*4 + styleNumber + 2) * 20);
	}
 }
}
public static void main(String[] args) {
	FontViewer myFontViewer = new FontViewer("Java's Fonts");
	myFontViewer.setSize(300,450);  myFontViewer.show();
}
} // end FontViewer

      


(4) Layout Managers

  - To maintain the same look and feel among various platforms we cannot make assumptions

- The layout of components in a container can be governed by a layout manager

- Each container has a default layout and a setLayout method for setting different layout policies

- If you don't like awt's layout policies you can create your own


Five Ready Layout Policies

Applets Basics

- Applet is a class in java.applet that has a lengthy hierarchy chain…

- The simplest Applet:

import java.applet.*;
public class My_Applet extends Applet {
}


HTML Containing Applets

 
  <html>
<head>
<title> My Applet </title>
</head>
<body>
My First Applet
<applet code = "MyApplet" height="100" width="200">
</applet>

</body>
</html>


Applet : Important Methods

init()

start
()

stop
()

destroy
()

paint
(Graphics g)

update
()
-> is first loaded

-> is viewable on the web page

-> stops been viewable

-> needs to stop completely

-> needs to be painted

-> needs to update the painting
 


Applet : A HelloWorld Example

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

public class HWApplet extends Applet {
    static final String message = "Hello World!";
    private Font myFont;

    public void init() {
       myFont = new Font("Helvetica", Font.BOLD, 48);
       setSize(350,130);
    }

    public void paint(Graphics g) {    
       // draw the black border of rectangle. 
       g.setColor(Color.black);
       g.drawRect(9, 9, 332, 102);  
       g.drawRect(8, 8, 334, 104);  
       g.drawRect(7, 7, 336, 106);        
       // lightgray rectangle
       g.setColor(Color.lightGray);
       g.fillRect(10, 10, 330, 100);
       // set the Helvetica font
       g.setFont(myFont);        
       // draw the shadow of the text
       g.setColor(Color.gray);
       g.drawString(message, 40, 75);       
       // draw the text
       g.setColor(Color.black);
       g.drawString(message, 37, 72);
    }
} // end class

 

A Scribble Application Example

import java.awt.*; //Import Classes of awt

public class Scribble extends Frame {

    private int last_x, last_y; //Last coordinates

    public Scribble(String _name) {
         super(_name); //To pass the title 
    } 
    // This method gets called each time the user
    // clicks on our Scribble-Frame
    public boolean mouseDown(Event e, int x, int y) {
       last_x = x;
       last_y = y;
       return true;
    } // end mouseDown

    // This method gets called each time the mouse gets dragged
    public boolean mouseDrag(Event e, int x, int y) {
       Graphics g = this.getGraphics();
       g.drawLine(last_x, last_y, x, y);
       last_x = x;
       last_y = y;
       return true;
    } // end method mouseDrag

    //This is the "entry point" where we instantiate an object
    //of type Scribble
    public static void main(String args[]) {
       Scribble my_scribble = new Scribble("Example Scribble");
       my_scribble.resize(200,200);
       my_scribble.show();
    } // end main

} //end Class Scribble
      

Passing Values From HTML

In html:

<applet code = "MyApplet" height="100" width="200">
<param name=colour value=blue>
</applet>
  In java source:

String extColour = getParameter("colour");

Security Constrictions for Applets

No File open/save

No Sockets, except to origin Server

No processes and execution of other programs

No replacing or tampering the Security manager

No Native methods


Placing an Applet in an Application

Just need to:

- create a Frame
- instantiate the applet
- add the applet to the Frame
- call : init, start, stop and destroy appropriately

You can do this because Applet is a Component


Quiz


1. Is it possible to place an Applet inside another Applet?

2. Is it possible to start a Frame from an Applet?

3. Class Graphics does not contain a method to set a pixel to a specific colour. How would you do it?

4. What will happen if you try to draw a shape which exceeds the limits of the applet’s bounds?

Exercises


1. Write a simple application which is composed of a Frame containing four buttons

2. Experiment with the following methods :
setBackground(Color c)
setTitle(String str)
setSize(width, height);

3. Write a simple application composed of a Frame and a Panel that has five buttons. Make each button to change the Frame’s background when pressed

4. Write a simple application composed of a Frame and paint into it 9 randomly coloured rectangles

5. Write a simple applet that draws a red rectangle, create its HTML page and execute it with the help of the appletviewer

6. Extend the previous applet to get its rectangle bounds from the HTML page

7. Write an applet that lets the user click and drag the mouse to create randomly coloured rectangles

8. Make the previous applet able to paint other shapes aswel as rectangles

 



Online Java Training, Applets, AWT, Graphics and Layouts


 
My other sites

Latest News

New Summer Look :)










Applets, AWT, Graphics and Layouts

  (3) AWT Graphics

The Graphics Class

Painting Into Graphics

Painting Into Graphics Example

Fonts

Fonts Example

(4) Layout Managers

Five Ready Layout Policies

Applets Basics

HTML Containing Applets

Applet : Important Methods

Applet : A First Example

A Scribble Application Example

Passing Values From HTML

Security Constrictions for Applets

Placing an Applet in an Application

Quiz

Exercises
 

 

(3) AWT Graphics

Numerous methods to draw lines, rectangles, circles, polygons, and images

Classes :

- Graphics

- Font, FontMetrics

- Color, SystemColor

- Dimension, Point

- MediaTracker

- java.awt.image.*


The Graphics Class

- Abstract Class used to draw on the screen and display images

- Protected Constructor

- Graphics is available to all the components on which the user may need to draw.

- These components need to implement :

public void paint(Graphics g)
update(Graphics g)

Painting Into Graphics

Most commonly used methods :

drawLine(x1, y1, x2, y2)

drawOval(x, y, width, height)

drawRect(x, y, width, height)

drawString(str, x, y)

setColor(Color)

setFont(Font)

fillRect(x, y, width, height)

draw3DRect(x, y, width, height, raised)

drawRoundRect(x, y, w, h, arcWidth, arcHeight)

 

Painting Into Graphics Example

 

import java.awt.*;

public class ShapesApplication extends Frame {
   static final String message = "Shapes!";
   private Font myFont;

   ShapesApplication(String str) {
     super(str);
     myFont = new Font("Helvetica", Font.BOLD, 36);
   }
   public static void main(String[] argv) {
    	ShapesApplication sa = 
                 new ShapesApplication("Shapes Example");
    	sa.setSize(400,300);
	sa.show();
   }
public void paint(Graphics g) {
   g.setColor(Color.black);
   g.setFont(myFont); // set Helvetica font
   g.setColor(Color.black);
   g.drawString(message, 150, 130); // draw the text      
   g.drawRect(10, 50, 80, 50); // draw two rectangles
   g.fillRect(10, 130, 80, 130);
   g.drawLine(100, 50, 180, 100); // draw one line
   int[] xPoints = {100, 120, 135, 160, 130};
   int[] yPoints = {70, 100, 160, 180,  100};
   g.drawPolyline(xPoints, yPoints, 5); 
   g.drawRoundRect(200, 50, 70, 50, 30, 30); 
   g.fillRoundRect(280, 50, 100, 50, 30, 30);     
   g.drawOval(200, 130, 50, 80); // draw 2 ovals    
   g.fillOval(270, 130, 100, 100); // draw 2 arcs
   g.drawArc(100, 200, 50, 70, 100, 100); 
   g.fillArc(150, 200, 80, 100, 130, 130);
  }  
  public boolean handleEvent(Event e) {
    if (e.id == Event.WINDOW_DESTROY) {
	dispose();
	System.exit(0);
	return true;
    }
    return super.handleEvent(e);
  }	    
} // end class
      

Fonts

- Represented in Java with the java.awt.Font class

- Small number of fonts, to promote platform independence

- Create a font by specifying a font family name, a font style and a point size

- Use setFont() on your Graphics object before calling drawString()


Fonts Example

 


 
import java.awt.*;
public class FontViewer extends Frame {
	public FontViewer(String s) {
	  super(s);
	}

// Available font names
String[] fontNames = {"Serif", "SansSerif",
         "Monospaced", "Dialog", "DialogInput"};

// Available styles names
String[] styleNames = {"Plain", "Italic", "Bold", "Bold Italic"};
int[] styles = {Font.PLAIN, Font.ITALIC, Font.BOLD,
                Font.ITALIC + Font.BOLD};
public void paint(Graphics g) {
 for (int fontNumber=0;fontNumber<fontNumber.length; fontNumber++) {
   for (int styleNumber=0; styleNumber < styles.length; styleNumber++) {
            Font f = new Font(fontNames[fontNumber],styles[styleNumber], 16);
	      String s = fontNames[fontNumber] + " " + styleNames[styleNumber];
	      g.setFont(f);
	      g.drawString(s, 10, (fontNumber*4 + styleNumber + 2) * 20);
	}
 }
}
public static void main(String[] args) {
	FontViewer myFontViewer = new FontViewer("Java's Fonts");
	myFontViewer.setSize(300,450);  myFontViewer.show();
}
} // end FontViewer

      


(4) Layout Managers

  - To maintain the same look and feel among various platforms we cannot make assumptions

- The layout of components in a container can be governed by a layout manager

- Each container has a default layout and a setLayout method for setting different layout policies

- If you don't like awt's layout policies you can create your own


Five Ready Layout Policies

Applets Basics

- Applet is a class in java.applet that has a lengthy hierarchy chain…

- The simplest Applet:

import java.applet.*;
public class My_Applet extends Applet {
}


HTML Containing Applets

 
  <html>
<head>
<title> My Applet </title>
</head>
<body>
My First Applet
<applet code = "MyApplet" height="100" width="200">
</applet>

</body>
</html>


Applet : Important Methods

init()

start
()

stop
()

destroy
()

paint
(Graphics g)

update
()
-> is first loaded

-> is viewable on the web page

-> stops been viewable

-> needs to stop completely

-> needs to be painted

-> needs to update the painting
 


Applet : A HelloWorld Example

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

public class HWApplet extends Applet {
    static final String message = "Hello World!";
    private Font myFont;

    public void init() {
       myFont = new Font("Helvetica", Font.BOLD, 48);
       setSize(350,130);
    }

    public void paint(Graphics g) {    
       // draw the black border of rectangle. 
       g.setColor(Color.black);
       g.drawRect(9, 9, 332, 102);  
       g.drawRect(8, 8, 334, 104);  
       g.drawRect(7, 7, 336, 106);        
       // lightgray rectangle
       g.setColor(Color.lightGray);
       g.fillRect(10, 10, 330, 100);
       // set the Helvetica font
       g.setFont(myFont);        
       // draw the shadow of the text
       g.setColor(Color.gray);
       g.drawString(message, 40, 75);       
       // draw the text
       g.setColor(Color.black);
       g.drawString(message, 37, 72);
    }
} // end class

 

A Scribble Application Example

import java.awt.*; //Import Classes of awt

public class Scribble extends Frame {

    private int last_x, last_y; //Last coordinates

    public Scribble(String _name) {
         super(_name); //To pass the title 
    } 
    // This method gets called each time the user
    // clicks on our Scribble-Frame
    public boolean mouseDown(Event e, int x, int y) {
       last_x = x;
       last_y = y;
       return true;
    } // end mouseDown

    // This method gets called each time the mouse gets dragged
    public boolean mouseDrag(Event e, int x, int y) {
       Graphics g = this.getGraphics();
       g.drawLine(last_x, last_y, x, y);
       last_x = x;
       last_y = y;
       return true;
    } // end method mouseDrag

    //This is the "entry point" where we instantiate an object
    //of type Scribble
    public static void main(String args[]) {
       Scribble my_scribble = new Scribble("Example Scribble");
       my_scribble.resize(200,200);
       my_scribble.show();
    } // end main

} //end Class Scribble
      

Passing Values From HTML

In html:

<applet code = "MyApplet" height="100" width="200">
<param name=colour value=blue>
</applet>
  In java source:

String extColour = getParameter("colour");

Security Constrictions for Applets

No File open/save

No Sockets, except to origin Server

No processes and execution of other programs

No replacing or tampering the Security manager

No Native methods


Placing an Applet in an Application

Just need to:

- create a Frame
- instantiate the applet
- add the applet to the Frame
- call : init, start, stop and destroy appropriately

You can do this because Applet is a Component


Quiz


1. Is it possible to place an Applet inside another Applet?

2. Is it possible to start a Frame from an Applet?

3. Class Graphics does not contain a method to set a pixel to a specific colour. How would you do it?

4. What will happen if you try to draw a shape which exceeds the limits of the applet’s bounds?

Exercises


1. Write a simple application which is composed of a Frame containing four buttons

2. Experiment with the following methods :
setBackground(Color c)
setTitle(String str)
setSize(width, height);

3. Write a simple application composed of a Frame and a Panel that has five buttons. Make each button to change the Frame’s background when pressed

4. Write a simple application composed of a Frame and paint into it 9 randomly coloured rectangles

5. Write a simple applet that draws a red rectangle, create its HTML page and execute it with the help of the appletviewer

6. Extend the previous applet to get its rectangle bounds from the HTML page

7. Write an applet that lets the user click and drag the mouse to create randomly coloured rectangles

8. Make the previous applet able to paint other shapes aswel as rectangles