Credits

Thursday, March 24, 2011

Event Handling in Java Graphics Class

Graphics class in Java allows the creation of geometric shapes like circle, square, arcs, lines and polygons.  More importantly, event handling is also possible. When we integrate event activities in a Graphic - oriented program, we simply employ the usual steps in embedding events: event interface, action listener, and event handler to respond.

The following methods are used to draw geometric shapes:

  • drawLine  ( ) - to draw a line
  • drawRect ( ) - to draw a rectangle or square
  • drawRoundRect ( ) - to draw a rectangle with arc or circle
  • drawOval ( ) - to draw an oval
  • drawPolygon ( ) - to draw any polygon
The  draw methods create only a border or outline shape, thus, if you wish to have a solid or shaded shape, a fill method is rather used. For instance, to draw a shaded rectange, we can write, fillRect ( ).

The program below illustrates the use of geometric methods and event handling.
[+/-] show/hide


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

public class GraphicsDemoCreateObject extends Applet implements ActionListener{
String companyName = new String (" S T I");
JButton moveButton = new JButton ("Move it.");
//Color newColor = new Color(100,20,255);//blue
Color newColor = new Color(255,20,255);
Font hell2Font = new Font ("Helvetica", Font.ITALIC, 12);
int x = 10, y = 50;

public void init()
{
setBackground(Color.yellow);
add(moveButton);

moveButton.addActionListener(this);
}

public void actionPerformed(ActionEvent e)
{
Graphics gr = getGraphics();
gr.setFont(hell2Font);
gr.setColor(newColor);
gr.drawString(companyName,x+=20,y+=20);
//the condition below is to control the movement within applet page size
if (y>getSize().height)
moveButton.setEnabled(false);
gr.setColor(Color.black);
gr.drawOval(50,170,70,70);
gr.drawLine(85,240, 110,300);
gr.drawOval(100,170, 70,70);
gr.drawLine(135,240,110,300);
setBackground(Color.blue);

}
}

AddThis