This file is BrickBreaker.java, the main file.
import javax.swing.JFrame;
public class BrickBreaker
{
public static void main(String[] args)
{
JFrame obj=new JFrame();
GamePlay gp=new GamePlay();
obj.setSize(700,600);
obj.setTitle("Generic Classic BrickBreaker");
obj.setResizable(true);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.add(gp);
}
}
Below is the second file GamePlay.java
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.event.KeyListener;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.Graphics;
import java.awt.Color;
public class GamePlay extends JPanel implements KeyListener, ActionListener
{
boolean play=true;
int score=0;
int totalBricks=21;
Timer time;
int delay=8;
int playerX=310;
int ballX=120;
int ballY=350;
int ballXdir=-1;
int ballYdir=-2;
public static void main(String[] args){}
public void GamePlay()
{
this.addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
time = new Timer(delay, this);
time.start();
}
public void paint(Graphics g)
{
g.setColor(Color.black);
g.fillRect(1,1,692,592);
g.setColor(Color.blue);
g.fillRect(0,0,3,592);
g.fillRect(0,0,692,3);
g.fillRect(691,0,3,592);
g.setColor(Color.blue);
g.fillRect(playerX,550,100,8);
g.setColor(Color.green);
g.fillOval(ballX,ballY,10,10);
g.dispose();
}
@Override
public void actionPerformed(ActionEvent e){
time.start();
}
@Override
public void keyTyped(KeyEvent e){
repaint();
}
@Override
public void keyReleased(KeyEvent e){}
@Override
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
{
if(playerX>=600)
{
playerX=600;
}
else
{
moveRight();
}
}
if(e.getKeyCode() == KeyEvent.VK_LEFT)
{
if(playerX<10)
{
playerX=10;
}
else
{
moveLeft();
}
}
repaint();
}
public void moveRight()
{
play = true;
playerX+=100;
}
public void moveLeft()
{
play = true;
playerX-=100;
}
}
What I have tried:
I have tried a lot of combinations and different placement of my repaint() function. I have also tried to make changes to the time.start() or the timer in general. I thought maybe that was causing the problem. It is a BrickBreaker game, I'm learning Java. The slider doesn't move when I press arrow keys and I can't seem to figure out what is wrong. I also checked if I'm updating the write variables and I think I am. Please help me, this is driving me crazy.