Program allows user to draw lines, ovals
and rectangles

Aim: 
To write a java program that allows the user to draw lines, rectangles and ovals.

Description: 
First create a class by extending Frame class and implement Mouse Listener interface. Override paint() method of Frame class. We can use methods of Graphics class to draw lines, rectangles and ovals. Provide the methods of wanted Mouse Listener interface and provide empty implementations to other methods of Mouse Listener interface.

Program:
import java.awt.*;
import java.awt.event.*;
public class DrawFigures extends Frame implements ActionListener, MouseListener
{
Button line, rect, oval;
int startX, startY, endX, endY, drawCode = 1;
public DrawFigures()
{ line = new Button("DRAW LINE");
line.addActionListener(this);
add(line);
rect = new Button("DRAW RECTANGLE");
rect.addActionListener(this);
add(rect);
oval = new Button("DRAW OVAL");
oval.addActionListener(this);
add(oval);
addWindowListener( new WindowAdapter()
{ public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
addMouseListener(this);
}
public void mouseClicked(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{ startX = e.getX();
startY = e.getY();
}
public void mouseReleased(MouseEvent e)
{ endX = e.getX();
endY = e.getY();
Graphics g = getGraphics();
if (drawCode == 1)
{ drawLine(g);
}
else if (drawCode == 2)
{ drawRect(g);
}
else
{ drawOval(g);
}
}
void drawLine(Graphics g)
{ g.drawLine(startX, startY, endX, endY);
}
void drawRect(Graphics g)
{
if (startX > endX)
{ g.drawRect(endX, endY, -(endX - startX), -(endY - startY));
}
else
{ g.drawRect(startX, startY, endX - startX, endY - startY);
}
}
void drawOval(Graphics g)
{
if (startX > endX)
{ g.drawOval(endX, endY, -(endX - startX), -(endY - startY));
}
else
{ g.drawOval(startX, startY, endX - startX, endY - startY);
}
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void actionPerformed(ActionEvent e)
{ if (e.getActionCommand().equals("DRAW LINE"))
{
drawCode = 1;
}
else if (e.getActionCommand().equals("DRAW RECTANGLE"))
{ drawCode = 2;
}
else
{ drawCode = 3;
}
}
public static void main(String[] args)
{
DrawFigures ob = new DrawFigures();
ob.setTitle("Draw Lines, Rectangles and Ovals");
ob.setLayout(new FlowLayout());
ob.setSize(500, 500);
ob.setVisible(true);
}
}