Thắc mắc đoạn code j2me

Cho mình hỏi đoạn code này
Mình có hàm VehinhV() và nó được gọi ở hàm dựng , thì hình được hiển thị
Nhưng gọi lại VehinhV() ở hàm keyPressed() .Thì nó llại không hiển thị hình, tại tọa độ mới khi mình tác động phím vào.

package mobileapplication4;

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.midlet.MIDlet;

/**
 *
 * @author vovan
 */
public class DH5 extends GameCanvas {
    int x=40;
    int y=40;
    Graphics g=super.getGraphics();
   DH5(MIDlet h) { 
       super (false);
        vehinhV();
       Display.getDisplay(h).setCurrent(this);
     
    }
   public void vehinhV(){
       System.out.println("vehinhV dc goi");
       g.setColor(255,0 , 0);
       g.drawRect(x, y, 32, 32);
       
   }
    public void keyPressed(int keyCode) {
     int v = super.getGameAction(keyCode);
        switch (v) {
            case LEFT:
                this.x = this.x - 32;
                break;
            case RIGHT:
                this.x = this.x + 32;
                break;
            case UP:
                this.y= this.y - 32;
                break;
            case DOWN:
                this.y = this.y + 32;
                break;
    }
       vehinhV(); 
    

}
}


Mình thử sử dụng hàm paint() , và hàm repaint() rồi bỏ hàm veHinhV trong hàm dựng thì nó lại vẽ theo ý mình muốn , Minh không hiểu tại sao ?

package mobileapplication4;

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.midlet.MIDlet;

/**
 *
 * @author vovan
 */
public class DH5 extends GameCanvas {
    int x=40;
    int y=40;
    Graphics g=super.getGraphics();
   DH5(MIDlet h) { 
       super (false);
      //  vehinhV();
       Display.getDisplay(h).setCurrent(this);
     
    }
   public void vehinhV(){
       System.out.println("vehinhCN dc goi");
       g.setColor(255,0 , 0);
       g.drawRect(x, y, 32, 32);
       
   }
   public void paint(Graphics g){
       this.g=g;
       vehinhV();
   }
    public void keyPressed(int keyCode) {
     int v = super.getGameAction(keyCode);
        switch (v) {
            case LEFT:
                this.x = this.x - 32;
                break;
            case RIGHT:
                this.x = this.x + 32;
                break;
            case UP:
                this.y= this.y - 32;
                break;
            case DOWN:
                this.y = this.y + 32;
                break;
    }
       //vehinhV(); 
       super.repaint();
    

}
}

Vì thế bạn nên vẽ trong phương thức paint().
Bạn hiểu nguyên lý hoạt động là màn hình luôn được vẽ lại khi có sự kiện hoặc repaint() được gọi. Khi vẽ lại, màn hình sẽ xóa đồ họa có trước đó, xóa sạch.

7 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?