Hello guys,
I was testing Java 2D and I tryed to make a game using Canvas and JFrame.There is interesting thing.For now it is drawing rectangle / square /, but when a key is pressed ( up ), it should be moving that rectangle, but it isn't..The Vector2f, which stores the position of the sprite is updated, but the sprite isn't repainted on a new position..
Code:
Window class:
public class Window extends Canvas implements Runnable {
private boolean isRunning = true;
private InputHandler inputHandler;
public static Vector2f positionOfTheSquare;
public Window() {
inputHandler = new InputHandler();
addKeyListener(inputHandler);
positionOfTheSquare = new Vector2f(675 / 2, 25);
}
public void paint(Graphics g) {
// g.drawRect(675 / 2, 25, 25, 25);
g.drawRect((int)positionOfTheSquare.x, (int)positionOfTheSquare.y, 25, 25);
}
public void update() {
if(inputHandler.keys[0] == true) {
positionOfTheSquare.y = positionOfTheSquare.y + 25;
}
}
public void render(Graphics g) {
}
public void run() {
while(isRunning == true) {
update();
}
}
}
InputHandler:
public class InputHandler implements KeyListener {
public boolean[] keys = new boolean[4];
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP) {
keys[0] = true;
System.out.println("Pressed Up!");
// Window.positionOfTheSquare.y = Window.positionOfTheSquare.y - 25;
}
// if(e.getK)
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP) {
keys[0] = false;
}
}
public void keyTyped(KeyEvent e) {
}
}
and the main class is:
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.setSize(new Dimension(640, 480));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
Window window = new Window();
frame.add(window);
frame.setVisible(true);
}
}
Any ideas?