I am not sure why my code is not working but it is driving me crazy.
This is my class that should draw the button and creates the area to draw on:
The second set of code is the driver program I need to make 4 canvas’s that when I make two mouse clicks it draws a line between the two clicks and then repaints if I try and click on a canvas again.
I get the following errors:
error: invalid method declaration; return type required
addMouseListener(this);
^
error: illegal start of type
addMouseListener(this);
^
public class Scribble extends JPanel implements MouseListener
{
addMouseListener(this);
int x, x1, y, y1;
boolean flag = false;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(x, y, x1, y1);
}
public void mouseReleased(MouseEvent e)
{
if (!flag){
x = e.getX();
y = e.getY();
flag = true;
}
else{
x1 = e.getX();
y1 = e.getY();
flag = false;
repaint();
}
}
public void mouseExited(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseMoved(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
}
public class Lab8Draw extends JFrame{
public Lab8Draw(){
Color c = new Color(100, 10, 200);
setTitle("Lab 8 - Application #1");
setLayout(new GridLayout(2,2));
Scribble s = new Scribble();
s.setBackground(Color.WHITE);
add(s);
Scribble s1 = new Scribble();
s1.setBackground(Color.RED);
add(s1);
Scribble s2 = new Scribble();
s2.setBackground(c);
add(s2);
Scribble s3 = new Scribble();
s.setBackground(Color.BLUE);
add(s3);
}
public static void main (String[] args){
Lab8Draw frame = new Lab8Draw();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 800);
frame.setVisible(true);
}
}
You will have to implement
MouseListenerand register it
The Java tutorials provide a useful guide to writing a
MouseListener.Alternatively, you could define an inner class that extends MouseInputAdapter as it already has empty implementations of the
MouseListenermethods.