【问题标题】:Smooth Motion with Java Swing使用 Java Swing 实现平滑运动
【发布时间】:2020-06-29 17:11:59
【问题描述】:

我在使用 java Swing 获得平滑流畅的运动时遇到了麻烦。使用此代码,其中涉及使用 BufferedImage 在将其应用到面板之前绘制图形,给我的结果是摇晃的运动和口吃。我该如何解决这个问题?

public class SmoothMotion extends JPanel {

    public static final int size = 800;
    public static int pos = 0;

    public static void main(String[] args) {
        JPanel panel = new SmoothMotion();
        JFrame frame = new JFrame("Smooth As");
        frame.setSize(size, size);
        frame.add(panel);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Timer timer = new Timer(17, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                SmoothMotion.updateItems();
                panel.repaint();
            }
        });
        timer.start();
    }

    public static void updateItems() {
        pos += 4;
        pos = pos > 750 ? 0 : pos;
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, size, size);
        g.setColor(Color.RED);
        g.fillRect(pos > 375 ? 750 - pos : pos, 100, 50, 50);
    }
}

【问题讨论】:

    标签: java swing


    【解决方案1】:
    1. 不要覆盖paint()。自定义绘画是通过覆盖paintComponent(...)

    2. 来完成的
    3. 不需要 BufferedImage。 Swing 默认情况下是双缓冲的。只需先调用super.paintComponent(graphics) 以清除背景,然后进行自定义绘画。

    4. 绘画方法不应改变类的属性。你应该有一个像updatePos(…) 这样的方法来更新位置。

    5. ActionLIstener 将调用 updatePos(),然后再调用 repaint()。

    请参阅:get width and height of JPanel outside of the class 以获取演示上述许多建议的示例。

    【讨论】:

    • 谢谢。我更新了我的代码以符合您的建议。我还将计时器间隔更改为更接近 60fps 的刷新率,并相应地增加了位置增量。不过,我似乎仍然口吃。我还能做些什么来获得更流畅的运动吗?我把修改后的代码放在我原来的帖子里。
    • 不要认为使用 Swing 可以做得更好。查看:gamedev.stackexchange.com/questions/34090/… 获取一些阅读材料。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    相关资源
    最近更新 更多