我如何使用DrawImage

时间:2014-07-18 00:31:33

标签: java

好的我真的很新java,我似乎无法让drawImage()工作,Plz帮助这是我的代码:

package Main;

import javax.swing.JFrame;

public class MainMethod extends JFrame{
    public MainMethod(){
        setTitle("Game");
        setContentPane(new GamePanel());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        pack();
        setVisible(true);
    }
    public static void main(String[] args){
        MainMethod MM = new MainMethod();
    }
}

我的班级与Drawimage

package Main;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class GamePanel extends JPanel implements Runnable{

//Variables
private static final int Height = 500;
private static final int Width = 500;
private static final int x = 225;
private static final int y = 225;

private boolean running = false;
private BufferedImage image;
private Graphics2D g2;
public Thread thread;

//constructor
public GamePanel(){
    super();
    setPreferredSize(new Dimension(500,500));
    setFocusable(true);
    requestFocus();
}

//addNotfity
public void addNotify(){
    if(thread == null){
        thread = new Thread(this);
        thread.start();
    }
}
//init
public void init(){
    running = true;
    image = new BufferedImage(Height, Width,BufferedImage.TYPE_INT_RGB);
    g2 = (Graphics2D) image.getGraphics();
}
//run
public void run() {
    init();

    while(running){
        drawChar(g2);
        try{
            Thread.currentThread();
            Thread.sleep(50);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

Image Rect = new ImageIcon("C:\\Users\\eduar_000\\Desktop\\Rect.png").getImage();

public void drawChar(Graphics2D g){
    g.drawImage(Rect, 225,225,null);
}

}

请帮助我,我不知道我做错了什么! Java对我来说真的很混乱!

1 个答案:

答案 0 :(得分:0)

你从未调用addNotify()来运行GamePanel类中的线程。

在MainMethod类构造函数中的setVisible(true)之后,添加对addNotify()方法的调用。

我在这里为你修好了:

package Main;

import javax.swing.JFrame;

public class MainMethod extends JFrame {

    public MainMethod() {
        setTitle("Game");
        GamePanel myPanel = new GamePanel();
        setContentPane(myPanel);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        pack();
        setVisible(true);
        myPanel.addNotify();
    }

    public static void main(String[] args){
        MainMethod MM = new MainMethod();
    }
}