0

我正在尝试学习编写我的第一个游戏,我想正确理解我所做的每一步。稍后我将面临双重缓冲和其他事情。我只是想在游戏循环中加载图像。我有两节课。第一个它只是一个调用 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();
    }

}
4

1 回答 1

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();

}
于 2013-07-17T15:00:01.097 回答