Hi,
I'm pretty new to
Java, and as such still struggle from basic problems.
My problem is how to do I link an action event from a button to a mouse event. This is being used in a program to allow users to draw a square, oval etc on a canvas by clicking their mouse button. They choose which shape to draw from the corresponding button. My problem is that the button is not reflecting the mouse click and vice-versa.
My code so far is as follows,
1. DrawToolCanvas class
import java.awt.*;
import java.awt.event.*;
public class DrawToolCanvas extends Canvas implements MouseListener, ActionListener
{
MouseEvent e;
public void paint(Graphics g)
{
}
public void actionPerformed(ActionEvent event)
{ if (event.getActionCommand().equals("square"))
mouseClicked(e);
else if (event.getActionCommand().equals("circle"))
circle();
}
public void circle()
{ Graphics g = getGraphics();
int x=getX(), y=getY();
g.setColor(Color.blue);
g.fillOval( x, y, x = 40, y = 40 );
g.setColor(Color.black);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e)
{
Graphics g = getGraphics();
int x=e.getX(), y=e.getY();
g.setColor(Color.red);
g.fillRect( x, y, x = 40, y = 40 );
g.setColor(Color.black);
}
}
2. DrawToolFrame class
import java.awt.*;
import java.awt.event.*;
public class DrawToolFrame extends Frame
implements WindowListener
{
DrawToolCanvas myCanvas;
public DrawToolFrame()
{
setTitle("Draw Tool Frame");
addWindowListener(this);
Button square, circle;
Panel myPanel = new Panel();
square = new Button("square"); square.setActionCommand("square");
circle = new Button("circle"); circle.setActionCommand("circle");
myPanel.add(square); myPanel.add(circle);
add("South", myPanel);
DrawToolCanvas myCanvas = new DrawToolCanvas();
add("Center", myCanvas);
square.addActionListener(myCanvas);
circle.addActionListener(myCanvas);
}
public void windowClosing(WindowEvent event) { System.exit(0); }
public void windowOpened(WindowEvent event) {}
public void windowIconified(WindowEvent event) {}
public void windowDeiconified(WindowEvent event) {}
public void windowClosed(WindowEvent event) {}
public void windowActivated(WindowEvent event) {}
public void windowDeactivated(WindowEvent event) {}
}
Any help would be appreciated.