i want my rectangle to stop when the user press both left and right key. I researched about multiple key handlings but couldnt manage to find anything.
package View;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GamePanel extends JPanel {
private final int WIDTH = 600, HEIGHT = 500;
// PROPERTIES
private Timer timer;
int x = 0;
int y = 475;
int velX = 0; // only left or right
// CONSTRUCTOR
public GamePanel() {
setSize(WIDTH, HEIGHT);
setBackground(new Color(240, 255, 255));
timer = new Timer(5, new MyTimerListener());
addKeyListener( new MyKeyListener());
setFocusable(true); // for key listening
setFocusTraversalKeysEnabled(false);
timer.start();
}
// METHODS
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor( new Color(201, 51, 51));
g.fillRoundRect(x, y, 80, 20, 15, 15);
}
public class MyTimerListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if ( x < 0 )
{
velX = 0;
x = 0;
}
if ( x > 520 )
{
velX = 0;
x = 520;
}
x = x + velX;
repaint();
}
}
public class MyKeyListener implements KeyListener {
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if ( code == KeyEvent.VK_LEFT )
velX = -1;
if ( code == KeyEvent.VK_RIGHT )
velX = 1;
}
@Override
public void keyReleased(KeyEvent e) {
velX = 0;
}
@Override
public void keyTyped(KeyEvent e) {}
}
}
thanks for heeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeelp
![two muppets]
So again, use Key Bindings and not a KeyListener. You would want to use separate bindings for key press and release for both right and left arrow keys, and will want to have your key binding actions change the state of your program that will effect how the Swing Timer moves the paddle. In this example here (borrowed from another example of mine), I've created an enum, Direction to encapsulate the right and left directions, and have created a
Map<Direction, Boolean>
that will associate a boolean with both right and left directions. A right arrow key press will change the map to associate the RIGHT direction with atrue
boolean, and key release would do the opposite. The Timer would poll the Map to see where to move the paddle. For example: