gpt4 book ai didi

java getGraphics()返回null,如何访问paintComponent?

转载 作者:行者123 更新时间:2023-12-02 06:06:40 24 4
gpt4 key购买 nike

我有一个带有 JPanel 和 PaintComponent() 的类。我还有一个实现 Runnable 的类,我计划在线程启动后将图像绘制到 PaintComponent 上。我的构造函数接收 JPanel,然后从那里调用 getGraphics()。然而,通过测试和搜索似乎总是返回 null。

    System.err.println("Thread Started");
isRunning = true;
System.err.println(pap.getGraphics());
Graphics g = pap.getGraphics(); //pap is the name of the JPanel
while (isRunning)
{
while(xPos <= pap.getWidth() + 1)
{
xPos+=horizontalDirection;
System.err.println(xPos);
drawImage(upImgs[1], xPos, yPos, g);
pap.repaint();
pause();
//g.drawOval(xPos, 10, 10, 10);
if(xPos >= pap.getWidth())
horizontalDirection = -horizontalDirection;
if(xPos < 1)
horizontalDirection = 1;
}
//pap.repaint();
//pause(); // let this thread sleep a bit
}
System.err.println("Thread Ended");

返回 线程已启动 2 无效的 线程“Thread-1”中的异常 java.lang.nullPointerException

我怎样才能正确地让paintComponent从这个单独的类中进行绘制?

最佳答案

你不能这么做。 Awt/Swing 不是线程安全的,因此绘图只能从 gui 线程完成。

关于java getGraphics()返回null,如何访问paintComponent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22232507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com