添加的BufferedImage只有2x2像素

时间:2011-08-06 23:54:33

标签: java swing paint bufferedimage

我有一个脚本循环(几乎像幻灯片)通过Vector对象(flipBook),使用Thread(animationThread),并将它们添加到JPanel。但是,添加的图像只有2x2像素大。 我已经确认图像是50x50,但它们似乎没有正确显示。

这是Thread实例背后的一些代码。我不完全确定哪个代码对查找源代码有帮助。

public void startThread() {
    if (flipWidth != 0 && flipHeight != 0) {
        System.out.println("[ AnimationAsset ] " + "We're starting the thread");
        Runnable r = new Runnable() {
            @Override
            public void run() {
                runWork();
            }           
        };
        animationThread = new Thread(r, "AnimationThread");
        animationThread.start();
        going = true;
    }
}
private void runWork() {
    try {
        while (going) {
            repaint();
            flipIndex = (flipIndex + 1) % numFlips;
            System.out.println("[ AnimationAsset ] flipIndex: " + flipIndex);
            Thread.sleep(1000);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        System.out.println("[ AnimationAsset ] " + "Interrupted");
    }
}
public void paint(Graphics g) {
    update(g);
}
public void update(Graphics g) {
    System.out.println("[ AnimationAsset ] " + flipIndex);
    ((Graphics2D) g).drawImage(flipBook.get(flipIndex), null, 5, 5);

}

2 个答案:

答案 0 :(得分:3)

  

并将它们添加到JPanel

这不是Swing代码。这是AWT代码。

使用Swing时,永远不会以这种方式覆盖update()和paint()方法。摆脱这些代码并重新开始。

要在Swing中执行此操作,我会使用带有Icon的JLabel并将标签添加到框架中。

然后,要在SWing中做动画,你应该使用Swing Timer

当计时器触发时,您只需使用标签的setIcon(...)方法将旧图标替换为新图标。

答案 1 :(得分:1)

嗯,你有一个奇怪的绘图代码

((Graphics2D) g).drawImage(flipBook.get(flipIndex), null, 5, 5);

您可以看到docs here...使用Graphic2D drawImage()方法

最常见的图像绘制方法是在JComponent上绘制图像,通常是JLabel。这是一个组件示例

public class MyLabel extends JLabel
{

private Image image;

public MyLabel(Image image)
{

this.image=image;

}

public void paintComponent(Graphics g)
{

  g.drawImage(this.image,x,y,width,height,null);

}

}

所以在这里你可以使用该组件作为常见的挥杆对象

public class MyPanel extends JPanel
{
 public MyPanel()
{
  Image image=null;
 try{
  image=ImageIO.read(new File("image.png"));
  }
 catch (IOException e) {
 }

  this.add(new MyLabel(image));

}

}
祝你好运