Just a heads up, I posted this same question on Dream in code over 2 hours ago and nobody has answered. The link is http://www.dreamincode.net/forums/topic/197275-checking-for-multiple-keys-pressed/page__p__1153044__fromsearch__1&#entry1153044
I have been trying to figure out how to increment or decrement a value if two keys are pressed at the same time (ctrl+, ctrl-). I cant seem to get it working. If you can lead me to an elementary example or give me some pointers I would appreciate it.
I am trying to make a race car, built from simple shapes, speed up and slow down when ctrl+ or ctrl- is pressed.
The part in red is what I was attempting.
Everything else works except that.
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Exercise16_15 extends JFrame {
public Exercise16_15() {
add(new raceCar());
}
class raceCar extends JPanel {
protected int xCordinate = 0;
protected int yCordinate = 150;
protected int z = 300;
public raceCar() {
int o = 0;
Timer timer = new Timer((200 + g), new ActionListener() {
public void actionPerformed(ActionEvent e) {
xCordinate += 10;
repaint();
}
});
timer.start();
}
private boolean locked = false;
private int twoPressed;
protected int g = 0;
public raceCar(int o) {
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (locked) {
switch (e.getKeyCode()) {
case KeyEvent.VK_PLUS:
g = -10000;
locked = true;
twoPressed = KeyEvent.VK_PLUS;
break;
case KeyEvent.VK_MINUS:
g = 10;
locked = true;
twoPressed = KeyEvent.VK_PLUS;
break;
case KeyEvent.VK_CONTROL:
locked = true;
twoPressed = KeyEvent.VK_CONTROL;
break;
default:
}
}
}
public void keyUp(KeyEvent e) {
if (e.getKeyCode() == twoPressed) {
locked = false;
}
}
});
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
yCordinate = getHeight();
z = getWidth();
g.setColor(Color.WHITE);
g.fillRect(0, 0, z, yCordinate);
Polygon raceCarParts = new Polygon();
raceCarParts.addPoint(xCordinate + 10, yCordinate - 20);
raceCarParts.addPoint(xCordinate + 20, yCordinate - 30);
raceCarParts.addPoint(xCordinate + 30, yCordinate - 30);
raceCarParts.addPoint(xCordinate + 40, yCordinate - 20);
if (xCordinate < z - 40) {
g.setColor(Color.BLACK);
g.fillOval(xCordinate + 10, yCordinate - 11, 10, 10);
g.fillOval(xCordinate + 30, yCordinate - 11, 10, 10);
g.setColor(Color.BLUE);
g.fillRect(xCordinate, yCordinate - 20, 50, 10);
g.setColor(Color.GREEN);
g.fillPolygon(raceCarParts);
g.setColor(Color.GREEN);
} else {
xCordinate = 0;
}
}
}
public static void main(String[] args) {
Exercise16_15 frame = new Exercise16_15();
frame.setTitle("Race Car");
frame.setSize(300, 150);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
}