如何在java中添加计时器来更改JTextPane的文本?

时间:2014-01-30 15:01:31

标签: java swing timer jtextpane

我正在研究一个java程序,我想要实现的是一旦窗口加载,JTextPane中的文本集就会改变。我有以下代码创建JTextPane;

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

我不确定如何添加一个会更改此JTextPane文本的计时器,2秒后,我需要它在程序加载后说准备就绪,然后在2秒后稳定,然后在2秒后,继续。< / p>

感谢。

1 个答案:

答案 0 :(得分:3)

您可能需要查看How to Use Swing Timers曲目。你可以这样做:

    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();

题外话

关于这个:

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

setBounds()的使用不是一个好习惯,因为swing应用程序必须能够在不同的平台上运行并且Look&amp;感觉。您应该让布局经理完成工作,避免使用setBounds()set(Preferred|Maximum|Minimum)Size

建议读物: