0
當我使用此代碼時,我的屏幕將爲空。所以這意味着 我的paintComponent方法有些問題。但是,什麼是錯的?我該如何解決它?我的預期輸出是一個深灰色的矩形和一個圖像。paintComponent方法將不起作用 - Java
代碼:
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;
}
}
}
}
感謝
感謝這個工作! –