Z
Z
zevilcube2019-08-24 21:23:07
Java
zevilcube, 2019-08-24 21:23:07

How to track two keys at the same time in Java?

There is a window:

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

class Window extends JFrame {

    private JPanel mainPanel;

    Window() {

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setLayout(null);
        setSize(1000+5,500+30);
        setResizable(false);
        setLocation((screenSize.width-1000)/2, (screenSize.height-500)/2);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);

        mainPanel = new JPanel();
        mainPanel.setBackground(Color.GREEN);
        mainPanel.setSize(getContentPane().getWidth(),getContentPane().getHeight());
        mainPanel.setVisible(true);

        add(mainPanel);
        repaint();
    }
}

Adding key listeners:
addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent e) {

                if (e.getKeyCode() == KeyEvent.VK_W) {
                    //do something here
                }
                if (e.getKeyCode()== KeyEvent.VK_A) {
                    //do something here
                }
                if (e.getKeyCode() == KeyEvent.VK_S) {
                    //do something here
                }
                if (e.getKeyCode() == KeyEvent.VK_D) {
                    //do something here
                }
                repaint();
            }
            public void keyReleased(KeyEvent e) {
            }
            public void keyTyped(KeyEvent e) {
            }
        });

Works great with my code, but how do I make it possible to track multiple key presses at the same time? For example, are W and D pressed.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Ernest Farukshin, 2019-08-24
@Ernest3

using KeyStroke

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question