Java Reference
In-Depth Information
if (getY()+getHeight ()+dy > panel . getHeight ()) {
dy = 1;
super .move(dx, dy);
}
}
The size of the ball and its initial coordinates are defined as constants. The constructor
of the ball creates a ball by calling the constructor of the BreakoutShape class. A ball will
be moved by changing its x and y coordinates. The ball should move with constant speed.
Therefore, we will move the ball by adding dx and dy to its x and y coordinates, respectively.
Therefore, ( x + dx , y + dy ) are the new coordinates of the ball. Note that the constructor of
the Ball class takes as input the panel in which the ball will move. The ball needs to know
about the panel so that it can bounce off the panel's walls.
Let us examine the move method in greater detail. Before the ball is moved, the value
of the variables dx of dy may need to be changed. For example, if x+dx <0 , this means that
the new value of x will be smaller than 0 and the value of dx needs to be made positive.
Similarly, if x+ballWidh+dx > panelWidth , then the new value of x will make the ball go
over the right corner of the screen and the value of dx needs to be made
1. The value of
dy is computed similarly.
Let us see how our code works so far. Here is the main class.
public class Breakout {
public static void main(String [] args) {
BreakoutFrame frame = new BreakoutFrame () ;
frame. setVisible( true );
}
}
The class simply creates the game window and makes it visible. Here is the code for the
game window.
import javax . swing . ;
import java .awt. event . ;
{
public class BreakoutFrame extends JFrame
private static final int HEIGHT = 600;
private static final int WIDTH = 488;
private BreakoutPanel panel = new BreakoutPanel () ;
public BreakoutFrame () {
setDefaultCloseOperation(JFrame.DISPOSEON CLOSE) ;
setLocation(100,100) ;
setSize(WIDTH, HEIGHT);
add(panel) ;
setResizable( false );
}
}
The setDefaultCloseOperation method assures that the window will be disposed of
when the close button is pressed. The width and the height of the window are set, where the
two numbers are defined as constants so that the dimensions of the window can be easily
changed. Finally, the panel is added to the window and the window is made non-resizable.
Let us next examine the code for the panel.
 
Search WWH ::




Custom Search