【问题标题】:Using JFrame to display an image through a loop使用JFrame通过循环显示图像
【发布时间】:2015-11-20 16:39:29
【问题描述】:

我有一个递归循环,它对图像执行计算,并希望通过每次迭代显示图像的进度。

这就是我所拥有的:

static JFrame colFrame = new JFrame();
main() {}

loop() {

        JLabel label = null;
        ImageIcon colIcon = new ImageIcon(blockImg);
        label = new JLabel(colIcon);
        colFrame.getContentPane().add(label);
        colFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // close canvas once the window is closed
        colFrame.pack();
        colFrame.setVisible(true);

}

有谁知道如何更改我的代码,以便在每次迭代中显示图像?

【问题讨论】:

    标签: java swing


    【解决方案1】:

    使用Swing Timer 来安排更改图像的动画。

    这是我每秒更改标签文本的简单示例:

    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.Timer;
    
    public class TimerTime extends JPanel implements ActionListener
    {
        private JLabel timeLabel;
        private int count = 0;
    
        public TimerTime()
        {
            timeLabel = new JLabel( new Date().toString() );
            add( timeLabel );
    
            Timer timer = new Timer(1000, this);
            timer.setInitialDelay(1);
            timer.start();
        }
    
        @Override
        public void actionPerformed(ActionEvent e)
        {
            //System.out.println(e.getSource());
            timeLabel.setText( new Date().toString() );
    //      timeLabel.setText( String.valueOf(System.currentTimeMillis() ) );
            count++;
            System.out.println(count);
    
            if (count == 10)
            {
                Timer timer = (Timer)e.getSource();
                timer.stop();
            }
        }
    
        private static void createAndShowUI()
        {
            JFrame frame = new JFrame("TimerTime");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add( new TimerTime() );
            frame.setLocationByPlatform( true );
            frame.pack();
            frame.setVisible( true );
        }
    
        public static void main(String[] args)
        {
            EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndShowUI();
                }
            });
        }
    }
    

    在您的情况下,您可能希望更改 Icon(而不是创建新标签)。

    【讨论】:

    • javax.swing.Timer 是一个不错的选择,但递归可能会很尴尬。
    • @trashgod,错过了递归部分。在适当的时候使用 Thread.sleep() 和 publish() 的 SwingWorker 可能更容易编码 (+1)。
    【解决方案2】:

    因为您的algorithm 是递归的,所以在SwingWorkerdoInBackground() 实现中调用它。在每个级别,publish() 一个 BufferedImage 代表当前状态,process() 它使用 label.setIcon()。生成BufferedImage 的示例显示为here,生成TexturePaint 的相关示例显示为here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      • 1970-01-01
      • 2014-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多