Java Reference
In-Depth Information
Going back to our drawing code, the mouse motion listener checks if the left mouse
button is pressed. If it is, it gets the current coordinates of the cursor and adds the point
to the current shape. The last line redraws the panel so that we can see the new shape.
When we draw too much on a sheet of paper, it may become cluttered and we may want to
clear it. We will fix this problem by allowing the panel to be cleared when the right mouse
button is pressed. Here is our complete code.
import
java .awt .
∗
;
import
java .awt. event .
∗
;
import
java .awt.geom.
∗
;
import
java . util .
∗
;
import
javax . swing .
∗
;
public class
DrawingGame
{
public static void
main(String [] args)
{
MyFrame f =
new
MyFrame ( ) ;
f . setVisible(
true
);
}
}
class
MyFrame
extends
JFrame
{
public
MyFrame ( )
{
setSize (300 , 300) ;
MyPanel p =
new
MyPanel () ;
add(p) ;
}
}
class
MyPanel
extends
JPanel
{
ArrayList
<
MyShape
>
shapes =
new
ArrayList
<>
() ;
public
MyPanel ()
{
addMouseListener(
new
MouseAdapter ()
{
public void
mousePressed (MouseEvent e )
{
if
(e . getButton() == 1)
{ // left mouse button
shapes .add(
new
MyShape( e . getPoint ( ) ) ) ;
repaint () ;
if
(e . getButton() == 3)
{
// right mouse button
shapes =
new
ArrayList
<>
() ;
repaint () ;
}
}
}
);
addMouseMotionListener(
new
MouseMotionAdapter ()
{
public void
mouseDragged(MouseEvent e)
{
if
((e. getModifiersEx() & MouseEvent.BUTTON1DOWN MASK)
! = 0 )
{
shapes . get(shapes . size ()
−
1) . addPoint(e . getPoint () ) ;
repaint () ;
}
}
}
);
}
public void
paintComponent(Graphics g)
{