Witam. Chciałbym napisać tak program aby postać zaczęła poruszać się gdy wciśnięty jest przycisk, a gdy nie to ma stać w miejscu. Niestety w moim programie postać rusza się cały czas gdy strzałka w prawo jest wcisnieta. Póki co chce zaimplementowac rucha prawo - lewo. W ActionListenerze w else {} musze cos wpisac, tylko nie wiem co. Próbowałem chyba wszystkiego i nic. Proszę o pomoc. Oto kod
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class ElectricManGameplay extends JPanel implements KeyListener, ActionListener
{
private ImageIcon Postać_w_Prawo1;
private ImageIcon Postać_w_Lewo1;
private int newXpositionMan;
private int newYpositionMan;
private int XpositionMan;
private int YpositionMan;
private boolean left = false;
private boolean right = false;
private int moves = 0;
private int delay = 100;
private Timer timer;
public ElectricManGameplay()
{
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(delay, this);
timer.start();
}
public void paint(Graphics g)
{
if(moves == 0)
{
XpositionMan = 100;
YpositionMan = 510;
}
g.setColor(Color.black);
g.drawRect(20, 20, 1455, 730);
g.setColor(Color.white);
g.fillRect(21, 21, 1454, 729);
Postać_w_Prawo1 = new ImageIcon("Postać_w_Prawo1.png");
Postać_w_Prawo1.paintIcon(this, g, XpositionMan, YpositionMan);
if(right)
{
Postać_w_Prawo1 = new ImageIcon("Postać_w_Prawo1.png");
Postać_w_Prawo1.paintIcon(this, g, XpositionMan, YpositionMan);
}
if(left)
{
Postać_w_Lewo1 = new ImageIcon("Postać_w_Lewo1.png");
Postać_w_Lewo1.paintIcon(this, g, XpositionMan, YpositionMan);
}
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_RIGHT) // jeśli przycisk (prawa strzałka) jest wciśnięty to wykonaj instrukcje
{
moves ++;
right = true;
left = false;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT)
{
moves ++;
right = false;
left = true;
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
public void actionPerformed(ActionEvent e)
{
if(right)
{
XpositionMan += 50;
}
else
{
}
repaint();
}
}