key listener is not responding

31 views Asked by At
public class Main {

    public static void main(String[] args){
        var gameWindow = new GameWindow();
        var gamePanel = new GamePanel();

        gamePanel.startGameThread();
    }
}



import javax.swing.*;

public class GameWindow extends JFrame {

    GameWindow() {
        var gamePanel = new GamePanel();

        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setTitle("Rycoon Alpha Version 0.1");
        this.setLocationRelativeTo(null);
        this.setVisible(true);

        this.add(gamePanel);
        this.pack();
    }
}



import javax.swing.*;
import java.awt.*;

public class GamePanel extends JPanel implements Runnable{

    final int originalTileSize = 16;
    final int scale = 6;

    final int tileSize = originalTileSize * scale;
    final int maxScreenCol = 10;
    final int maxScreenRow = 6;
    final int screenWidth = tileSize * maxScreenCol;
    final int screenHeight = tileSize * maxScreenRow;

    KeyInput keyI = new KeyInput();
    Thread gameThread;

    int playerX = 250;
    int playerY = 480;
    int playerSpeed = 4;

    public GamePanel(){
        this.addKeyListener(keyI);
        this.setPreferredSize(new Dimension(screenWidth,screenHeight));
        this.setBackground(Color.CYAN);
        this.setDoubleBuffered(true);
        this.setFocusable(true);
    }

    public void startGameThread(){

        gameThread = new Thread(this);
        gameThread.start();
    }

    @Override
    public void run() {

        while(gameThread != null){

            update();
            repaint();
        }
    }

    public void update(){

        if(keyI.jumped == true){
            playerY -= playerSpeed;
            System.out.println("test");
        }



    }

    public void paintComponent(Graphics g){

        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;

        g2.setColor(Color.white);
        g2.fillRect(playerX, playerY, tileSize, tileSize);
        g2.dispose();
    }
}



import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class KeyInput implements KeyListener {

    public boolean jumped = false;

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {

        int code = e.getKeyCode();

        if(code == KeyEvent.VK_W){
            jumped = true;
            System.out.println("hi");
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
}

I've tried switching to different key inputs but I can't even get it to print anything

0

There are 0 answers