为什么我的图像运动在使用按键绑定移动时如此不稳定?

问题描述 投票:0回答:1

所以我做了这个图像绘制课,当我按 a 或 d 键时,运动一开始非常不稳定,但大约一秒钟后就变得有点平滑。这是为什么?我该如何解决它?

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;

public class GameWindow extends JPanel {
    Image map;
    int x = 0, y = 0;
    boolean isLeft = false, isRight = false;
    Action left;
    Action right;
    Action hleft;
    Action hright;
    public GameWindow(BufferedImage map){
        this.map = map.getScaledInstance(map.getWidth()*4, map.getHeight()*4, Image.SCALE_DEFAULT);
        left = new Left();
        right = new Right();
        hleft = new HLeft();
        hright = new HRight();
        setFocusable(true);
        requestFocus();
        Timer t = new Timer(42, new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(isLeft && !isRight){
                    x-=5;
                } else if (!isLeft && isRight) {
                    x+=5;
                }
                repaint();
            }
        });

        getInputMap().put(KeyStroke.getKeyStroke("pressed D"), "s move left");
        getActionMap().put("s move left", left);

        getInputMap().put(KeyStroke.getKeyStroke("pressed A"), "s move right");
        getActionMap().put("s move right", right);

        getInputMap().put(KeyStroke.getKeyStroke("released D"), "h move left");
        getActionMap().put("h move left", hleft);

        getInputMap().put(KeyStroke.getKeyStroke("released A"), "h move right");
        getActionMap().put("h move right", hright);

        t.start();
    }


    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(map, x, y, null);
    }
    public class Left extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            isLeft=true;
            //System.out.println("TEST");
        }
    }
    public class Right extends  AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            isRight = true;
        }
    }
    public class HRight extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            isRight = false;
        }
    }
    public class HLeft extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            isLeft = false;
        }
    }
}


我尝试搜索导致断断续续的运动的原因,但我唯一能找到的是启动计时器,而不是在按键绑定/动作侦听器中移动图像,但它仍然断断续续

编辑:我使用 Java 21.0.2,运行 Debian 12。我联系了一些朋友,在一些朋友上运行顺利(Windows、Arch),而在其他人(我的电脑和 Kali)上则卡顿。

java linux swing
1个回答
0
投票

我在这里找到了答案:为什么我的java图形滞后这么多?

显然放置

Toolkit.getDefaultToolkit().sync()
可以解决问题,尽管我不太清楚为什么。

将其放在这里,以防其他人遇到这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.