Java – game code behaves differently between MAC and windows

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



public class Game extends JFrame implements KeyListener
{
    private int charX;
    private int charY;

    public Game()
    {
        charX = 250;
        charY = 450;
        this.setSize(500,500);
        addKeyListener(this);
        this.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
    }


    public void keyTyped(KeyEvent event)
    {
        if(event.getKeyChar() == 'a')
            charX-=5;
        else if(event.getKeyChar() == 'd')
            charX+=5;
        else if(event.getKeyChar() == 'w')
            charY-=5;
        else if(event.getKeyChar() == 's')
            charY+=5;
        if(charX > 485)
            charX-=6;
        else if(charX < 10)
            charX+=6;
        if(charY > 485)
            charY-=6;
        else if(charY < 30)
            charY+=6;
        repaint();
    }

    public void keyPressed(KeyEvent event)
    {
    }

    public void keyReleased(KeyEvent event)
    {
    }

    public void paint(Graphics g)
    {
        super.paint(g);
        g.setColor(Color.BLACK);
        g.fillRect(charX,charY,10,10);
    }

    public static void main(String args[])
    {
        Frame frm = new Game();
        frm.setVisible(true);
        frm.repaint();
    }
}

I use a Mac at school and a PC with windows 10 at home. On the Mac, this code behaves differently from the Windows version In the Mac version, things go as expected, and the character (square) moves only a little each time you press a key But on windows, if in any direction (e.g. d), the role will continue to move to the right, even if it should only be called once Not only that, the frame flashes constantly when painting So I want to know why there are differences between MAC and windows versions, and how I can solve the flicker problem on windows I'm going to add keypressed and keyreleased methods later, so I don't think I'll have such a bad time

Solution

Critical events differ between operating systems When Mac OS may create only one key, windows may quickly create typed events when the key is turned off

The solution is to use key bindings instead of key events, although you may be lucky to find a combination of keypressed and keyreleased for both operating systems (it is still recommended to use only key bindings)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>