Pausing Swing GUI

坚强是说给别人听的谎言 提交于 2019-12-18 09:52:40

问题


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 the button I want the text field to start typing itself with a delay. So for example:

textfield.text=h
wait(1) sec
textfield.text=he
wait(1) sec
textfield.text=hel
wait(1) sec
textfield.text=hell
wait(1) sec
textfield.text=hello

I have already tried with Thread.sleep(), but in the example above it waits 4 seconds or so and after that displays the whole text (so it's not giving me the typo effect that I would want).

Can somebody help me with this?


回答1:


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++;
}



回答2:


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?



来源:https://stackoverflow.com/questions/23023730/pausing-swing-gui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!