指定字符串display java

时间:2014-06-05 19:18:12

标签: java

我想知道如何用Java显示一个字符串(逐个字符),也就是说,在JTextField中显示一个char,然后在2秒后再显示另一个?

有人能指出我如何解决这个问题吗?

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
   String s = jTextField4.getText (), s1 = "";
   String str = "";
   int L = s.length();
   int x = 1500;
   for (int i=0; i< L; i++) 
   {
        char prem = s.charAt(i);
        str= str + prem;
        x = x + 2000;
        final Thread th4 = new Thread (new  Runnable() {
            public void run() {
                try {
                    Thread.sleep(x);
                } catch (InterruptedException ex) {                 
                }
            }
        });
        th4.start();
        s1 = s1.concat(str);
        jTextField3.setText(s1);
    }
}

1 个答案:

答案 0 :(得分:0)

这应该做的工作

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
   Thread thread = new Thread(new DelayedWriter(jTextField3, jTextField4.getText()));
   thread.start();
}

class DelayedWriter implements Runnable{
    JTextField tf;
    String s;
    public DelayedWriter(JTextField tf, String s){
        this.tf = tf;
        this.s=s;
    }
    public void run(){
        for (int i=0; i< s.length(); i++) 
        {
            tf.setText(s.substring(0,i+1));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {

            }
        }
    }
}