Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

java - Lag spike when moving player

The player is a panel, and it is getting removed, its position changed, and then re-added to another panel (which is what contains this method) which is drawn to the main frame. There are also a lot of other small panels containing a grass sprite being drawn to the primary panel as terrain tiles. I think the problem is that when I call revalidate(), it revalidates all those little panels as well. How can I solve this?

EDIT: I should mention that I am using RelativeLayout to position the players on the primary panel.

private class MainKeyAdapter extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent evt) {
        // TODO add your handling code here:
        if(AttentionedPlayer != null)
        {
            if (evt.getKeyCode() == KeyEvent.VK_UP) {
                AttentionedPlayer.Ypos -= 16;
            }
            if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
                AttentionedPlayer.Ypos += 16;
            }
            if (evt.getKeyCode() == KeyEvent.VK_LEFT) {
                AttentionedPlayer.Xpos -= 16;
            }
            if (evt.getKeyCode() == KeyEvent.VK_RIGHT) {
                AttentionedPlayer.Xpos += 16;
            }
            remove(AttentionedPlayer);
            AttentionedPlayer.movePlayer();
            System.out.println("!!!!"+AttentionedPlayer.constraints.toString());
            add(AttentionedPlayer, AttentionedPlayer.constraints, AttentionedPlayer.Zpos);
            AttentionedPlayer.revalidate();
        }
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

AttentionedPlayer.movePlayer(); seems to be an intensive operation, and you execute it from within EDT (the GUI thread). Instead, execute it from within a new thread or a SwingWorker.

Read this answer to know more about SwingWorker.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...