使用java swing计时器处理文本并将其附加到textarea
我有一个JTextArea txtProcess和两个要处理的方法: 第一种方法是使用for循环处理小于10的乘法。将它们相乘后,所有结果都将使用计时器附加到txtProcess 我使用定时器来延迟追加。例如,附加到txtProcess的第一个结果。500毫秒后,第二个结果附加到txtProcess。依此类推,直到所有结果都附加到txtProcess 像这样:使用java swing计时器处理文本并将其附加到textarea,java,swing,timer,actionlistener,jtextarea,Java,Swing,Timer,Actionlistener,Jtextarea,我有一个JTextArea txtProcess和两个要处理的方法: 第一种方法是使用for循环处理小于10的乘法。将它们相乘后,所有结果都将使用计时器附加到txtProcess 我使用定时器来延迟追加。例如,附加到txtProcess的第一个结果。500毫秒后,第二个结果附加到txtProcess。依此类推,直到所有结果都附加到txtProcess 像这样: int a = 10; int result = 0; for(int i=1; i <= a; i++){ result
int a = 10;
int result = 0;
for(int i=1; i <= a; i++){
result = i * a;
txtProcess.append("Result "+ i +" = "+ result);
}
但是,第一个和第二个方法同时执行。这是第二个问题:在第一种方法和第二种方法之间创建间隔时间。我怎样才能解决这个问题
注意:
你可能会认为这个问题是重复的。我已经阅读并尝试了那里的代码,但仍然无法解决问题 计时器所做的是在每次达到间隔时执行
ActionListener
中的代码。
所以,如果您希望文本追加10次,那么在侦听器中不能有for循环。计时器将为您处理循环
ActionListener listener = new ActionListener(){
private int counter = 0;
@Override
public void actionPerformed( ActionEvent e ){
txtProcess.append("Result "+ counter +" = "+ result);
counter++;
if ( counter == 10 ){
((Timer)e.getSource()).stop();
}
}
}
Timer timer = new Timer( 500, listener );
timer.start();
我没有仔细检查上面的代码,因此它可能包含语法错误或循环太多/比需要的少一倍。它更能说明
计时器的用法
好的,我明白了。第一个问题解决了。第二个问题呢?@Speaky如果你理解我的答案,你应该知道为什么会出现第二个问题
void second(){
ActionListener listen = new ActionListener(){
public void actionPerformed(ActionEvent e){
for(int i=1; i <= a; i++){
result = i * a;
txtProcess.append("Result "+ i +" = "+ result +"\n");
if(i == 9){
((Timer)e.getSource()).stop();
}
}
}
};
Timer mine = new Timer(500, listen);
mine.start();
}
void combine(){
ActionListener listen = new ActionListener(){
public void actionPerformed(ActionEvent e){
first();
second();
}
};
Timer mine = new Timer(500, listen);
mine.start();
}
ActionListener listener = new ActionListener(){
private int counter = 0;
@Override
public void actionPerformed( ActionEvent e ){
txtProcess.append("Result "+ counter +" = "+ result);
counter++;
if ( counter == 10 ){
((Timer)e.getSource()).stop();
}
}
}
Timer timer = new Timer( 500, listener );
timer.start();