Adding a timer and displaying label text

后端 未结 1 1298
日久生厌
日久生厌 2020-12-06 23:58

I have a JLabel. Initially i have set some text to it.

JLabel j = new JLabel();
// set width height and position

j.setText(\"Hello\");

I o

相关标签:
1条回答
  • 2020-12-07 00:41

    Swing is a event driven environment, one of the most important concepts you need to under stand is that you must never, ever, block the Event Dispatching Thread in any way (including, but not limited to, loops, I/O or Thread#sleep)

    Having said that, there are ways to achieve you goal. The simplest is through the javax.swing.Timer class.

    public class TestBlinkingText {
    
        public static void main(String[] args) {
    
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException ex) {
                    } catch (InstantiationException ex) {
                    } catch (IllegalAccessException ex) {
                    } catch (UnsupportedLookAndFeelException ex) {
                    }
    
                    JFrame frame = new JFrame();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new BlinkPane());
                    frame.setSize(200, 200);
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
    
            });
    
        }
    
        protected static class BlinkPane extends JLabel {
    
            private JLabel label;
            private boolean state;
    
            public BlinkPane() {
                label = new JLabel("Hello");
                setLayout(new GridBagLayout());
    
                add(label);
                Timer timer = new Timer(5000, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        label.setText("Good-Bye");
                        repaint();
                    }
                });
                timer.setRepeats(false);
                timer.setCoalesce(true);
                timer.start();
            }
        }
    }
    

    Check out

    • The Event Dispatch Thread
    • How to Use Swing Timers

    For more information

    0 讨论(0)
提交回复
热议问题