我单击一个JButton,我应该在JTextField中获得下面的最终输出:
01234567
我想设置一个Timer,因此每个数字的结果都会缓慢显示。
例如(在JTextField中),我希望的结果应该是这样的: 0(1秒后) 01(1秒后) 012(1秒后) 0123 .......... 01234567 (JTextField中的输出为01234567)
我目前正在使用Thread.sleep,但我没有得到我想要的结果。 我首先点击JButton: (1秒后) 01234567
我目前正在使用代码
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
textfield.setText("");
for (int i=0; i<8; i++)
{
textfield.setText(i);
Thread.sleep(1000);
}
}
catch (InterruptedException e1) {
e1.printStackTrace();
}
}
});
有没有办法使用Timer而不更改&#34; button.addActionListener(new ActionListener()......&#34; ??(如果我使用Timer,我希望不使用Thread.sleep)
答案 0 :(得分:4)
使用Swing Timer和Timer的actionPerformed方法将被重复调用,这将是你的“循环”。因此,摆脱方法中的for循环,绝对摆脱Thread.sleep(...)
ActionListener timerListener = new ActionListener(){
private String text = "";
private int count = 0;
public void actionPerformed(ActionEvent e){
text += // something based on count
count++;
textField.setText(text);
// code to stop timer once count has reached max
}
});
例如,
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
@SuppressWarnings("serial")
public class Tester extends JPanel {
public static final int TIMER_DELAY = 1000;
public static final String TEST_TEXT = "01234567";
private JTextField textField = new JTextField(10);
private JButton button = new JButton(new ButtonAction());
private Timer timer;
public Tester() {
add(textField);
add(button);
}
private class ButtonAction extends AbstractAction {
public ButtonAction() {
super("Press Me");
putValue(MNEMONIC_KEY, KeyEvent.VK_P);
}
@Override
public void actionPerformed(ActionEvent e) {
if (timer != null && timer.isRunning()) {
return;
}
textField.setText("");
timer = new Timer(TIMER_DELAY, new TimerListener());
timer.start();
}
}
private class TimerListener implements ActionListener {
private String text = "";
private int counter = 0;
@Override
public void actionPerformed(ActionEvent e) {
text += TEST_TEXT.charAt(counter);
textField.setText(text);
counter++;
if (counter >= TEST_TEXT.length()) {
timer.stop();
}
}
}
private static void createAndShowGui() {
Tester mainPanel = new Tester();
JFrame frame = new JFrame("Tester");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
答案 1 :(得分:0)
我认为你必须放textfield.setText(textfield.getText()+i)
,因为如果你不这样做,你会覆盖实际内容