游戏环境中的Java drawimage

时间:2013-07-17 14:08:57

标签: java loops graphics paint repaint

我正在努力学习编写我的第一个游戏,并且我想正确理解我所做的每一步。我稍后会面对双缓冲和其他事情。 我只是想在游戏循环中加载图像。 我有两节课。第一个只是一个调用start方法的jframe。 我想知道是否有一些丑陋的代码,在这里(我想是这样)。 那么,为什么我的图像没有显示出来?

public class myPanel extends JPanel implements Runnable{

//FIELDS
public static int WIDTH = 1024;
public static int HEIGHT = WIDTH / 16 * 9;
private BufferedImage bg;
private BufferedImage charac;
private boolean running;
private Thread t1;
private int startposX = WIDTH / 2;
private int startposY = HEIGHT / 2;
private int cordX = startposX;
private int cordY = startposY;
int speed = 50;


//METHODS   
public synchronized void start (){
    running = true;
    t1 = new Thread (this);
    t1.start();
}

public synchronized void stop (){
    running  = false;
    try {
        t1.join();
        System.out.println("The game stopped");
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
              }
 }

 //INIT
 public myPanel(){

   setPreferredSize(new Dimension(WIDTH, HEIGHT));
   setFocusable(true);
   requestFocus();
   addKeyListener(this);
 }

 //MAIN RUN METHOD

 public void run(){
           while (running){
           load();
           System.out.println("The game runs");
           repaint();
          }
 }


  //PAINT WITH GRAPHICS METHOD
  public void paint (Graphics g){
    super.paint(g);
    g.drawImage(bg, 0, 0, this);
    g.drawImage(charac, 110, 280, this);

}

//LOAD IMAGES IN MEMORY
public void load (){
            try {
        String path1 = "res/bg.png";
        bg = ImageIO.read(new File (path1));
        String path2 = "res/charac.png";
        charac = ImageIO.read(new File (path2));
    } catch (IOException e) {

        e.printStackTrace();
    }

}

1 个答案:

答案 0 :(得分:0)

所以,我做了一些关于paint vs paintcomponent的测试,我刚看到第一个绘制在jpanel背景之上。无论如何,我仍然看不到任何改变行的内容

    public void run(){
    while (running){
    load();
    System.out.println("The game runs");

    }
}



    //PAINT WITH GRAPHICS METHOD

    public void paintComponent (Graphics g){
    super.paint(g);
    g.drawImage(bg, 0, 0, null);
    g.drawImage(charac, 110, 280, null);
    }
//LOAD IMAGES METHOD AS ABOVE

是的,我已经将面板添加到框架中,这是另一个类

公共课游戏{

public static void main (String [] args){

JFrame frame = new JFrame();
frame.setIgnoreRepaint(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new myPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

myPanel game = new myPanel();
game.start();

}