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
478 views
in Technique[技术] by (71.8m points)

swing - Problems with Java's Paint method, ridiculous refresh velocity

I'm developing a very simple version of R-Type as work for the university, but despite it works, the craft velocity is a lot of slow, so the movement is ugly and clumsy. I use the method repaint for refresh the screen, there are others methods or ways best than it?

Video of Movement

Paint method at main Panel

@Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
        g2.drawImage(fondo, 0, 0,1200,600,this);
        pj.paint(g2);
        g2D=g2;

    }

PJ's paint method

public void paint(Graphics2D g) {

    g.drawImage(imagen,x,y,this);
}

PJ's move method

public void move (KeyEvent e)  {
    int dx = 0; int dy = 0;
    int code = e.getKeyCode();

    switch (code) {
    case KeyEvent.VK_Q: dy-=1; break;
    case KeyEvent.VK_A: dy+=1; break;
    case KeyEvent.VK_P: dx+=1; break;
    case KeyEvent.VK_O: dx-=1; break;
    }

    int x = (getX()<maxX&&getX()!=0) ? getX()+dx : getX();
    int y = (getY()<maxY&&getY()!=0) ? getY()+dy : getY();

    if (getY()>=maxY||getY()==0) {
        if (dy==+1) y=y+1;
    }

    setPosicion(x, y); 

}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
  • The image fondo should already be scaled to 1200x600.
  • I am not sure, but is super.paint(g) needed? You might also use paintComponent.

The event handling (you seem to be moving by 1 pixel on key down), must be done correctly. I would have set the direction and speed (1px), and leave it to a swing timer to do the continuous moving.

Repainting best is done resilient/flexible: repaint(20L) (50 frames per second); events like key-down maybe with EventQueue.invokeLater(new Runnable() { ... });.

Especially you might use repaint with the changed area.


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

...