Java Reference
In-Depth Information
public class Paddle extends BreakoutShape
{
private static final int START X = 200;
private static final int START Y = 430;
private static final int WIDTH = 5 0 ;
private static final int HEIGHT = 1 0 ;
private static final int SPEED = 1 0 ;
private BreakoutPanel panel ;
public Paddle(Color color , BreakoutPanel panel ) {
super ( new Rectangle2D .Double(STARTX, Paddle .STARTY , P a d d l e . WIDTH,
P a d d l e . HEIGHT) ,
c o l o r , true );
this . panel = panel ;
}
public void move( int dx)
{
if ((getX() + dx
>
= 0 ) && ( g e t X ( ) + d x + WIDTH
<
=panel.getWidth())
) {
move(dx , 0) ;
}
}
public void moveRight ()
{
move (SPEED) ;
}
public void moveLeft ()
{
move( SPEED) ;
}
}
Note that we need a reference to the bounding panel in order to ensure that the paddle
does not move outside the panel. We have two sets of move methods. The moveLeft and
moveRight methods will be used to move the paddle in response to the key listener. For
example, when the left button is pressed, the paddle will move to the left by 10 pixels.
The speed of the paddle is declared as a private constant and can be easily modified. The
move method will be used by the mouse listener and it needs finer granularity. For example,
moving the mouse slightly to the left can move the paddle by one pixel. The paddle is
moved by calling the move method of the BreakoutShape superclass. Note that the second
parameter of the call is 0, which means that the paddle will not move vertically.
Our design does not allow someone from outside the Paddle class to move the paddle
outside the panel or even move the paddle in non-horizontal direction. Restricting the paddle
movement in this way is a good design because it helps us easily isolate buggy code. For
example, if the paddle was moving diagonally instead of horizontally, we know that the
error must be somewhere in the Paddle class.
Next, let us examine how to modify the BreakoutPanel class to support the paddle.
In the constructor of the class we need to create a paddle object. In the paintComponent
method we need to call the draw method on the paddle object in order to display it. We
also need to add a key listener and a mouse listener to the panel that move the paddle.
This can be done, for example, in the constructor of the panel. Here is the updated version
of the BreakoutPanel class.
import javax . swing . ;
import java .awt . ;
import java .awt. event . ;
 
Search WWH ::




Custom Search