paintComponent方法不起作用 - Java

时间:2015-11-08 19:25:45

标签: java swing awt paint

当我使用此代码时,我的屏幕将为空。这意味着 我的paintComponent方法有问题。但有什么不对?我该如何解决?我的预期输出是深灰色矩形和图像。

代码:

package _47b3n.seg.main.engine;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import _47b3n.seg.main.frame.Frame;

public class Engine extends JPanel {

public int xOff;
public int yOff;
public int x;
public int y;
public int fpsInt = 199;

public boolean isRunning = true;

public FPS fps = new FPS();

public static void main(String [] args) {
    Frame frame = new Frame();
    frame.setFrame(800, 600, "Super easy game", "0.0.1");
    new Engine();
}

public Engine() {
    start();
}

public void move() {
    x+=xOff;
    y+=yOff;
}

public void start() {
    Thread loop = new Thread () {
        public void run() {
            gameLoop();
            addKeyListener(new keyInput());
        }
    };
    loop.start();
}


public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.DARK_GRAY);
    g.fillRect(10, 10, 10, 10);
    g.drawImage(new ImageIcon("Poppetje.jpg").getImage(), x, y, null);
}

public void gameLoop() {
    while(isRunning) {
        move();
        repaint();
        fps.update();
        fpsInt++;
        if (fpsInt == 200) {
            System.out.println("[Console] " + fps.getFPS() + " FPS");
            fpsInt = 0;
        }
        try {Thread.sleep(17);} catch (InterruptedException e) {e.printStackTrace();}
    }
}   

public class keyInput extends KeyAdapter {

    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();

        if(key == KeyEvent.VK_W) {
            yOff = -1;
        }

        if (key == KeyEvent.VK_S) {
            yOff = 1;
        }

        if (key == KeyEvent.VK_A) {
            yOff = -1;
        }

        if (key == KeyEvent.VK_D) {
            xOff = 1;
        }
    }

    public void keyReleased(KeyEvent e) {
        int key = e.getKeyCode();


        if (key == KeyEvent.VK_W) {
            yOff = 0;

        }

        if (key == KeyEvent.VK_S) {
            yOff = 0;
        }

        if (key == KeyEvent.VK_A) {
            xOff = 0;
        }

        if (key == KeyEvent.VK_D) {
            xOff = 0;
        }

    }

}

}

由于

1 个答案:

答案 0 :(得分:4)

不知道这是否是唯一的问题,但您从不将面板添加到框架中:

//new Engine();
Engine engine = new Engine();
frame.add(engine);
frame.setVisible(true);