paintComponent 方法不起作用 - Java
Posted
技术标签:
【中文标题】paintComponent 方法不起作用 - Java【英文标题】:paintComponent method won't work - Java 【发布时间】:2016-02-09 10:39:46 【问题描述】:当我使用此代码时,我的屏幕将为空。所以这意味着 我的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】:不知道这是否是唯一的问题,但您从未将面板添加到框架中:
//new Engine();
Engine engine = new Engine();
frame.add(engine);
frame.setVisible(true);
【讨论】:
以上是关于paintComponent 方法不起作用 - Java的主要内容,如果未能解决你的问题,请参考以下文章
使用 JPanel 的 addMouseListener() 和 paintComponent()