Java Reference
In-Depth Information
import javax . swing . ;
import java .awt . ;
import java .awt. event . ;
public class BreakoutPanel extends JPanel
private javax . swing .Timer timer ;
private Ball ball ;
public BreakoutPanel () {
ball = new Ball (Color . red , this );
timer = new javax . swing .Timer(10 , new ActionListener ()
public void actionPerformed(ActionEvent e)
ball .move() ;
repaint () ;
timer. start() ;
public void paintComponent(Graphics g)
super . paintComponent(g) ;
Graphics2D g2 = (Graphics2D) g ;
ball .draw(g2);
Note that we have used javax.swing.Timer as the timer class. The reason is that
there is more than one class that is called Timer . Alternatively, we could have imported
javax.swing.Timer andonlyreferredtothe Timer class in the code.
The constructor of the class creates the ball and the timer and starts the timer. When
the 10 milliseconds expire, the coordinates of the ball are updated and the panel is repainted.
The paintComponent method creates the two-dimensional brush and uses it to draw the
ball. If we run the program so far, we will see the ball bouncing off the walls.
When working on a non-trivial software, it is always a good idea to start with a
small feature and test it. Next, build the program from there. Adding small features
one at a time and testing them has the advantage that it is easier to isolate any
errors. If one writes a big program (e.g., more than 1000 lines) without testing it, then
it will be dicult to isolate the errors. Note that errors are not the product of bad
programming. Every time non-trivial code is written, errors will emerge. The hallmark
of good software practices is to identify and correct errors as early as possible in the
11.4 Adding the Paddle
Next, let us add the paddle to the game. The Paddle class will be similar to the Ball
class. However, the main difference is that it can only move horizontally. Here is the code
for the Paddle class.
Search WWH ::

Custom Search