Set dynamic JLabel text in a JDialog by timer

后端 未结 4 855
终归单人心
终归单人心 2020-12-21 18:10

Im trying to make a JDialog that will show the user a dynamic message on a JLabel. The message should be a count from 1 to 10 (and it should be changing a number every secon

4条回答
  •  余生分开走
    2020-12-21 18:57

    Have a look at this code example, that's the proper way to use dynamic text with the help of javax.swing.Timer Tutorials, instead of using Thread.sleep(...) thingy,

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class DialogExample extends JDialog
    {
        private Timer timer;
        private JLabel changingLabel;
        private int count = 0;
        private String initialText = "TEXT";
    
        private ActionListener timerAction = new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                count++;
                if (count == 10)
                    timer.stop();
                changingLabel.setText(initialText + count); 
            }
        };
    
        private void createDialog()
        {
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            setLocationByPlatform(true);
    
            JPanel contentPane = new JPanel();
            changingLabel = new JLabel(initialText);
            contentPane.add(changingLabel);
    
            add(contentPane);
    
            pack();
            setVisible(true);
            timer = new Timer(1000, timerAction);
            timer.start();
        }
    
        public static void main(String... args)
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    new DialogExample().createDialog();
                }
            });
        }
    }
    

提交回复
热议问题