import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import game.Racket.DIRECTION;
@SuppressWarnings("serial")
public class GamePanel extends JPanel implements Runnable, KeyListener {
private final GraphicsConfiguration gfxConf = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration(); // used to create image for drawing
private BufferedImage imageBuffer = null; // used to draw graphics
private boolean running = false; // @see running
private Thread animator = null; // thread for game ticks
RacketHorizontal racket = new RacketHorizontal(70, 20);
public GamePanel(int width, int height) {
setPreferredSize(new Dimension(width, height));
racket.setColor(Color.BLUE);
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
racket.setDirection(DIRECTION.LEFT);
if (key == KeyEvent.VK_RIGHT)
racket.setDirection(DIRECTION.RIGHT);
}
@Override
public void keyReleased(KeyEvent e) {
racket.setDirection(DIRECTION.NO_MOVE);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (imageBuffer == null || imageBuffer.getWidth() != getWidth() || imageBuffer.getHeight() != getHeight()) {
imageBuffer = gfxConf.createCompatibleImage(getWidth(), getHeight());
}
if (imageBuffer != null)
g.drawImage(imageBuffer, 0, 0, this);
}
@Override
public void run() {
while (running) { // false -> stops game
try {
updatePosition(); // update objects positions
updateGraphics(); // draw graphics
Thread.sleep(5); // 1000 / 5 update game every 200 millisecond
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void startGame() {
stopGame();
while (animator != null && animator.isAlive())
;
animator = new Thread(this);
running = true;
animator.start();
}
public void stopGame() {
running = false;
}
/**
* do graphic manipulations here
*/
public void updateGraphics() {
if (imageBuffer != null) {
Graphics g = imageBuffer.createGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
racket.draw(g);
}
repaint();
}
/**
* do position manipulations here
*/
private void updatePosition() {
racket.move();
}
}