使用Swing Timers

时间:2017-01-20 23:56:28

标签: java swing

为什么以下代码不起作用? 我想创建一个将BufferedImage绘制到JPanel上的应用程序。因此,只要您启动该程序,您就会看到它在绘制图像。我了解到你需要Swing计时器,所以我尝试实现它们。现在我希望程序在每个水平绘制的像素线x之后休眠。因此,在重绘()之后,我希望JPanel停止绘画几毫秒,之后它应该绘制下一行。但是我做错了什么?

提示:方法createPicture提供一个矩阵,其int值转换为颜色。

public class ImagePanel extends JPanel{
    int[][] matrix = new int[1920][1080];
    private BufferedImage image;
    int x=0,y=0;

    ActionListener taskPerformer = new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
              if(y==1079||x==1919){  //as soon as the image is ready             
                  ((Timer)evt.getSource()).stop();
              }else{
              for(y=0;y<1080;y++){
               for(x=0;x<1920;x++){
                   image.setRGB(x,y,matrix[x][y]);
               }repaint();
               //I want it to sleep here
               }
              } 
              }
      }; 

    public ImagePanel() throws IOException, InterruptedException{
        image = new BufferedImage(1920,1080, BufferedImage.TYPE_INT_RGB);
         createPicture(1920,1080);
          new Timer(200, taskPerformer).start();
       }

1 个答案:

答案 0 :(得分:2)

  

现在我希望程序在每个水平绘制的像素线x之后休眠。

当您使用TimerActionListener中的所有代码都会在每次Timer触发时执行(并且您不想在监听器中使用sleep() )。因此,您无法在Timer内执行两个循环。

相反,你需要做的只是增加&#34; y&#34;侦听器中的图像值,然后绘制该行的所有像素。所以你只需要一个循环。

代码可能类似于:

ActionListener taskPerformer = new ActionListener() 
{
    int y = 0;

    public void actionPerformed(ActionEvent evt) 
    {
        for(x=0;x<1920;x++)
        {
            image.setRGB(x,y,matrix[x][y]);
        }

        repaint();

        y++;

        if (y >= ???)
            ((Timer)evt.getSource()).stop();
    }
}; 

请注意,您也不应该对x / y值最大值进行硬编码。相反,您可以使用getWidth()的{​​{1}}和getHeight()方法。

此外,当您第一次创建BufferedImage时,您需要绘制其背景,否则您尚未更改的像素将为黑色。