Simple Paddle in Brick Breaker
Code for simple paddle in java brick breaker game
import java.awt.Color;import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import test1.BallBreaker;
public class Bat extends JPanel{
private int x = 140;
private int y = 240;
int width = 30;
int height = 10;
public Bat(){
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent evt) {
moveIt(evt);
}
});
setFocusable(true);
}
public void paint(Graphics g)
{
/*
*
* As we are extending JPanel,
* we need to paint background with some color first
* Note: if we extend Canvas class than we need not
* paint back ground. we can directly draw peddle
*/
g.setColor(Color.LIGHT_GRAY);//paint background with light gray
g.fillRect(0, 0, 350, 450);//screen dimensions
g.setColor(Color.blue);//change color value from gray to blue
g.drawRect(x, y, width, height);
g.fillRect(x, y, width, height);//fill blue color to paddle
/*
* you can uncomment below two lines to see styles of peddle
*/
// g.fill3DRect(x, y+40, width, height, false);
// g.fill3DRect(x, y+80, width, height, true);
}
protected void moveIt(KeyEvent evt) {////finds which key is pressed eighter left of right
if (x < 3) {
x = 3;
} else if (x > 290) {
x = 290;
}
switch (evt.getKeyCode()) {
case KeyEvent.VK_LEFT:
x -= 5;
break;
case KeyEvent.VK_RIGHT:
x += 5;
break;
}
repaint();
}
//public int getX() {
// return x;
//}
//
//public void setX(int x) {
// this.x = x;
//}
//
//public int getY() {
// return y;
//}
//
//public void setY(int y) {
// this.y = y;
//}
public static void main(String[] args) {
Bat bat = new Bat();
JFrame jf = new JFrame("game");
jf.add(bat);
jf.setSize(350,450);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}