Reputation: 13
I'm trying to move left or right a rectangle in JFrame
but when I use the arrow buttons the bar is not moving; it's just extending. The rectangle is for the Brick Breaker type of game.
public class main
{
public static void main(String[] args)
{
JFrame obj = new JFrame("Brick Breacker");
obj.setBounds(50,50,1200,900);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setVisible(true);
Grafica grafica = new Grafica();
obj.add(grafica);
}
}
public class Grafica extends JPanel implements ActionListener , KeyListener
{
Timer tm = new Timer(0,this);
boolean play = false;
int playerX = 550;
int playerXs = 0;
public Grafica()
{
tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paint (Graphics g)
{
//paddle
g.setColor(Color.GREEN);
g.fillRect(playerX, 800, 145, 10);
//borders
g.setColor(Color.BLACK);
g.fillRect(0, 0, 5, 900);
g.fillRect(1180, 0, 5, 900);
g.fillRect(1200, 0, -1200, 5);
g.setColor(Color.RED);
g.fillRect(1200, 860, -1200, 5);
//ball
g.setColor(Color.blue);
g.fillOval(550,700, 26, 26);
}
public void actionPerformed(ActionEvent e)
{
playerX = playerX + playerXs;
repaint();
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
playerXs = 0;
}
public void keyPressed(KeyEvent e)
{
int c = e.getKeyCode();
if( c == KeyEvent.VK_RIGHT )
{
if(playerX > 850)
{
playerX = 850;
} else
{
moveRight();
}
}
if(c == KeyEvent.VK_LEFT)
{
if(playerX > 850)
{
playerX = 850;
} else
{
moveLeft();
}
}
}
public void moveRight()
{
play = true;
playerX+=20;
}
public void moveLeft()
{
play = true;
playerX-=20;
}
}
Upvotes: 1
Views: 52
Reputation: 1366
The reason this is not working is that your paint() implementation does not clear the background, i.e. you are drawing the green bar multiple times - retaining the already painted areas. Thus it looks like the bar is elongating instead of moving.
You shouldn't override the paint(Graphics)
method, but instead the paintComponent(Graphics)
method, and you should invoke super.paintComponent(Graphics)
:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// Now do your own painting here...
}
The call to the super class implementation will give you the initialization of the Graphics context, including clearing it with the background color of your JPanel.
You can read more on how to do custom painting in Swing components here.
Also, as a side note, the range limitation to the right works, but the one to the left doesn't - it should check for playerX < 0
.
And finally, the way you implement your game loop - by responding to key inputs and repainting - is not optimal. Google for 'java game loop' to get ideas on how to do this in a better way (very briefly: Your game loop should be independent on the input and should update the scene at regular intervals. The input events should then change the game state, which should be reflected in the next scene update).
Upvotes: 2