Witam, robię symulator samochodu i chciałbym, aby po wciśnięciu klawisza "W" zwiększała się prędkość, lecz nic się nie dzieje... Mógłby ktoś doradzić?
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Color;
@SuppressWarnings("serial")
public class CarSimulator extends JPanel {
int predkosc;
int obroty;
int bieg;
boolean silnikOdpalony = false;
Timer timer;
int delay = 33;
private JTextField txtPredkosc;
private JTextField txtBieg;
private JTextField txtObroty;
public CarSimulator() {
setBackground(Color.LIGHT_GRAY);
setLayout(null);
JPanel panel = new JPanel();
add(panel);
panel.setLayout(null);
panel.addKeyListener(new SpeedListener());
JLabel lblPredkosc = new JLabel("Predkosc:");
lblPredkosc.setHorizontalAlignment(SwingConstants.RIGHT);
lblPredkosc.setBounds(217, 29, 68, 14);
add(lblPredkosc);
JLabel lblBieg = new JLabel("Bieg:");
lblBieg.setHorizontalAlignment(SwingConstants.RIGHT);
lblBieg.setBounds(217, 60, 68, 14);
add(lblBieg);
JLabel lblObroty = new JLabel("Obroty:");
lblObroty.setHorizontalAlignment(SwingConstants.RIGHT);
lblObroty.setBounds(217, 91, 68, 14);
add(lblObroty);
JButton btnStart = new JButton("START");
btnStart.setBounds(232, 183, 135, 70);
add(btnStart);
txtPredkosc = new JTextField();
txtPredkosc.setText("0");
txtPredkosc.setHorizontalAlignment(SwingConstants.CENTER);
txtPredkosc.setColumns(10);
txtPredkosc.setBounds(297, 26, 86, 20);
txtPredkosc.setEditable(false);
add(txtPredkosc);
txtBieg = new JTextField();
txtBieg.setText("N");
txtBieg.setHorizontalAlignment(SwingConstants.CENTER);
txtBieg.setColumns(10);
txtBieg.setBounds(297, 57, 86, 20);
txtBieg.setEditable(false);
add(txtBieg);
txtObroty = new JTextField();
txtObroty.setText("0");
txtObroty.setHorizontalAlignment(SwingConstants.CENTER);
txtObroty.setColumns(10);
txtObroty.setBounds(297, 88, 86, 20);
txtObroty.setEditable(false);
add(txtObroty);
}
public class SpeedListener implements KeyListener {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_W) {
setPredkosc(1);
txtPredkosc.setText(Integer.toString(getPredkosc()));
}
}
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_W) {
setPredkosc(-1);
txtPredkosc.setText(Integer.toString(getPredkosc()));
}
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
public void setPredkosc(int predkosc) {
this.predkosc += predkosc;
}
public int getPredkosc() {
return predkosc;
}
}