代码如下:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;public class InvokeLaterTest extends JFrame{
private JTextArea jta=new JTextArea();
private JButton jb=new JButton("click");
public InvokeLaterTest(){
jta.setBounds(new Rectangle(20,50,200,200));
jb.setBounds(new Rectangle(20,20,100,20));
jb.addActionListener(new click());
Container cp=getContentPane();
cp.setLayout(null);
cp.add(jta);
cp.add(jb);
}
class click implements ActionListener{
public void actionPerformed(ActionEvent e) {
jta.append("the first row\n");
try{
Thread.sleep(2000);
}catch(InterruptedException ex){
throw new RuntimeException(ex);
}
jta.append("the second row");
}
}
public static void main(String[] args){
Console.run(new InvokeLaterTest(),300,300);
}
}
我希望在按了click按钮后,jta显示the first row以后,过几秒再显示the second row,但实际效果是:按了click按钮后,jta延迟了2秒,然后把the first row和the second row一起显示出来了。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;public class InvokeLaterTest extends JFrame{
private JTextArea jta=new JTextArea();
private JButton jb=new JButton("click");
public InvokeLaterTest(){
jta.setBounds(new Rectangle(20,50,200,200));
jb.setBounds(new Rectangle(20,20,100,20));
jb.addActionListener(new click());
Container cp=getContentPane();
cp.setLayout(null);
cp.add(jta);
cp.add(jb);
}
class click implements ActionListener{
public void actionPerformed(ActionEvent e) {
jta.append("the first row\n");
try{
Thread.sleep(2000);
}catch(InterruptedException ex){
throw new RuntimeException(ex);
}
jta.append("the second row");
}
}
public static void main(String[] args){
Console.run(new InvokeLaterTest(),300,300);
}
}
我希望在按了click按钮后,jta显示the first row以后,过几秒再显示the second row,但实际效果是:按了click按钮后,jta延迟了2秒,然后把the first row和the second row一起显示出来了。
import java.awt.*;
import java.awt.event.*;public class InvokeLaterTest extends JFrame{
private JTextArea jta=new JTextArea();
private JButton jb=new JButton("click");
private boolean temp=false;
public InvokeLaterTest(){
jta.setBounds(new Rectangle(20,50,200,200));
jb.setBounds(new Rectangle(20,20,100,20));
jb.addActionListener(new click());
Container cp=getContentPane();
cp.setLayout(null);
cp.add(jta);
cp.add(jb);
}
class test extends Thread{
public test(){
start();
}
public void run(){
if(temp==false){
temp=true;
jta.append("the first row\n");
}else{
try{
System.out.println("fsddfds");
Thread.sleep(2000);
}catch(InterruptedException ex){
throw new RuntimeException(ex);
}
jta.append("the second row");
}
}
}
class click implements ActionListener{
public void actionPerformed(ActionEvent e) {
new test();new test();
}
}
public static void main(String[] args){
Console.run(new InvokeLaterTest(),300,300);
}
}