简体   繁体   中英

How to add a timer to change text of a JTextPane in java?

I am working on a java program, what I want to implement is once the window loads, the set of text in a JTextPane to change. I have the below code that creates the JTextPane;

JTextPane txtpnReady = new JTextPane();
        txtpnReady.setText("Ready");
        txtpnReady.setEditable(false);
        txtpnReady.setBounds(181, 39, 169, 20);
        contentPane.add(txtpnReady);

I am unsure of how to add a timer that will change the text of this JTextPane, after 2 seconds, I need it to say Ready once the program loads, then after 2 seconds Steady and then after 2 seconds, Go.

Thanks.

You may want to take a look to How to Use Swing Timers trail. You can do something like this:

    Timer timer = new Timer(2000, new ActionListener() {

        private String nextText = "Steady";

        @Override
        public void actionPerformed(ActionEvent e) {
            txtpnReady.setText(nextText);
            if(!nextText.equals("Go")) {                    
                nextText = "Go";
            } else {
                ((Timer)e.getSource()).stop();
            }
        }
    });

    timer.setRepeats(true);
    timer.setDelay(2000);
    timer.start();

Off-topic

About this:

txtpnReady.setBounds(181, 39, 169, 20);

The use of setBounds() is not a good practice since swing applications must be able to run on different platforms and Look & feels. You should let layout managers do their job and avoid the use of setBounds() and set(Preferred|Maximum|Minimum)Size .

Suggested readings:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM