如何在另一个线程中绘制jframe?

smtd7mpg  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(362)

我想做一个jframe的 paint() 方法启动一个线程,然后使用 Graphics 从该线程渲染形状(在单独的文件中)。当我试着这样做的时候,没有任何效果。

//JFrame
public class Window extends JFrame {

    public Window() {

        this.setTitle("Test");
        this.setSize(1280, 720);
        this.setLocationRelativeTo(null);
        this.setVisible(true);

    }

    public void paint(Graphics g) {
        new ThreadForRendering(g).start();
    }
// Thread I'm trying to run
public class ThreadForRendering extends Thread {

    private final Graphics g;

    public ThreadForRendering(Graphics g) {
        this.g = g;
    }

    public void run() {
        this.g.setColor(Color.RED);
        this.g.fillRect(0, 0, 500, 500);
    }
}

我试过添加 super.paintComponent(g); 到paint方法,并调用 repaint() 在线程启动后的窗口中,但窗口仍为空。

ldxq2e6h

ldxq2e6h1#

paint 作为对gui线程上需要的重新绘制的响应而调用,应该很快发生。打破这一计划只会带来问题,黑屏是最不用担心的。 @Override public void paintComponent 应该是你的绘画实现。应该很快。
如果你有复杂而缓慢的东西要画,你可以填一个表格 BufferedImage 然后你可以在 paintComponnent .

private AtomicReference<BufferImage> imgRef = new AtomicReference<>();

@Override
public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    BufferedImage img = img.get();
    if (img != null) {
        g2.draw img ...
    }
}

在线程中:

BufferedImage constructedImg = new ...
Graphics g = constructedImg.createGraphics();
try {
    g.fillRect ...
} finally {
    g.dispose();
}
imgRef.set(constructedImg);

通常,绘制是智能完成的:jpanel通常是双缓冲的,绘制是在缓冲区中完成的,然后覆盖实际显示的缓冲区。所以在大多数情况下,不需要解析到另一个线程。

相关问题