【问题标题】:Graphics.drawImage from another Thread does not draw anything in Java Swing来自另一个线程的 Graphics.drawImage 不会在 Java Swing 中绘制任何内容
【发布时间】:2017-03-22 09:06:27
【问题描述】:

我正在尝试通过将所有帧显示为BufferedImage 对象并使用ThreadJPanels paintComponent(Graphics g) 方法中为每个帧调用g.drawImage 来在JPanel 中绘制动画,中间有睡觉。我的理解是从任何地方调用g.drawImage,只要gpaintComponent中的Graphics对象,应该会导致JPanel中的像素被更新,但@没有变化987654332@。这不是Graphics.drawImage 的工作方式,还是使用另一个Thread 或其他所有东西的问题?下面是我的代码的缩写版本,删除了不必要的部分

class Example extends JPanel{

    public Dimension getPreferredSize(){
        return new Dimension(500, 500);
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        draw(g);
    }

    public void draw(Graphics g){
        BufferedImage temp1;
        BufferedImage temp2;
        try{
            temp1 = ImageIO.read(new File("C:\\Users\\Owner\\Desktop\\test1.png"));
            temp2 = ImageIO.read(new File("C:\\Users\\Owner\\Desktop\\test2.png"));
        }catch(IOException e){
            temp1 = null;
            temp2 = null;
        }
        final BufferedImage image1 = temp1;
        final BufferedImage image2 = temp2;
        Thread drawThread = new Thread(new Runnable(){
            public void run(){
                g.drawImage(image1, 0, 0, null);
                try{
                    Thread.sleep(100);
                }catch(InterruptedException e){
                    // omitted
                }
                g.drawImage(image2, 0, 0, null);
                try{
                    Thread.sleep(100);
                }catch(InterruptedException e){
                    // omitted
                }
            }
        });
        drawThread.start();
    }

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new B());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
           }
        });
    }

}

【问题讨论】:

    标签: java multithreading image swing graphics


    【解决方案1】:

    您当前的绘画代码错误。绘画方法仅用于绘画。您永远不会从绘画方法开始线程。您无法控制何时调用绘画方法,并且每次调用该方法时都会启动另一个线程。

    Graphics 对象应仅用作在绘画方法期间存在的短期对象。您不应尝试无限期地保留对该对象的引用。

    我正在尝试绘制动画

    如果你想做动画,那么你可以使用Swing Timer 来安排动画。

    因此,您应该将图像作为类的属性。然后当Timer 触发时,您更改图像属性并在面板上调用repaint()

    【讨论】:

      猜你喜欢
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-30
      • 2011-11-05
      • 2011-11-30
      相关资源
      最近更新 更多