Pausing Swing GUI

前端 未结 2 1437
我寻月下人不归
我寻月下人不归 2020-12-22 08:21

Hy! So I\'m starting with netbeans java gui development and I have run into this problem:

I have made a window with a button and a text field. When the user clicks t

相关标签:
2条回答
  • 2020-12-22 08:55

    Got it working by using something like this:

    Timer a,b,c
    
    Timer c=new Timer(500, new ActionListener(){public void actionPerformed(ActionEvent e){textfield.setText(abc)}})
    
    Timer b=new Timer(500, new ActionListener(){public void actionPerformed(ActionEvent e){textfield.setText(ab);c.start()}})
    
    Timer a=new Timer(500, new ActionListener(){public void actionPerformed(ActionEvent e){textfield.setText(a);b.start()}})
    
    a.setRepeats(false);
    b.setRepeats(false);
    c.setRepeats(false);
    
    a.start()
    

    Does anybody know a more simple method with the same effect maybe?

    0 讨论(0)
  • 2020-12-22 09:01

    If you use Thread.sleep(...) or any other code that delays the Swing event thread, you'll end up putting the entire Swing event thread to sleep, and with it your application. The key here is to instead use a Swing Timer. In the Timer's ActionListener's actionPerformed method, add a letter and increment your index, and then use that index to decide what letter to next add.

    i.e.,

    String helloString = "hello";
    
    // in the Timer's ActionListener's actionPerformed method:
    if (index >= helloString.length()) {
      // stop the Timer here
    } else {
      String currentText = textField.getText();
      currentText += helloString.charAt(index);
      textField.setText(currentText);
      index++;
    }
    
    0 讨论(0)
提交回复
热议问题