phân biệt paint(Graphics g ) và paintComponent(Graphics g)

0 nhận xét
Lần trước tôi đã dùng Applet để viết 1 tấm ảnh có thể chạy được, lần này tôi viết tấm ảnh chạy trên JPanel . dưới đssy là code mẫu , không phải toàn bộ project

Đây source code mẫu

import java.awt.Graphics;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Heart extends JPanel{
    private ImageIcon heart;
    private static int x = 10;   
    private Tuyen1 t ;
    Heart(){
        heart = new ImageIcon("heart.png");        
        setBackground(Color.WHITE);
        t = new Tuyen1();          
        t.start();
    }
    public void paintComponent(Graphics g){
        super.paintComponent( g ); // nếu thiếu dòng này sẽ k đẹp.
        heart.paintIcon(this,g,x,10);
    }   
    public class Tuyen1 extends  Thread{
        public void run(){
            try {
                        sleep( 1*1000);
                    }catch (InterruptedException e) {}
            while(true){
                while ( x <500){    
                    x +=1;                   
                    try {
                        sleep( 1*10);
                    }catch (InterruptedException e) {}
                        repaint();
                }   
                while ( x >10){    
                    x -=1;                   
                    try {
                        sleep( 1*10);
                    }catch (InterruptedException e) {}
                        repaint();
                }                  
            }
        }
    }    
}
Các bạn hãy chú ý là nếu chạy trên Applet thì hảnh ta thấy sẽ bị giựt , còn nếu dùng hàm paintComponent(Graphics g) thì ảnh chuyển động sẽ mượt hơn. các bạn có thể thử
Mến chào các bạn.

0 nhận xét:

Đăng nhận xét

Copyright 2011 learn java.
Blogger Template by Noct. Free Download Blogger Template