我想在一个按钮按下后,写一个过程更新JTextArea中的内容,但是我发现只有当这个ActionListener执行完之后,内容才会得到更新。如:
import java.awt.GridLayout;
import java.awt.event.*;import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;public class TextAreaTest extends JFrame {
private JTextArea t;
private JButton b;
private void test() {
t.append("B\n");
try {
Thread.sleep(2000);
}
catch (Exception ex) {}
t.append("C\n");
}
public void test2() {
t.append("B\n");
try {
Thread.sleep(2000);
}
catch (Exception ex) {}
t.append("C\n");
}
public TextAreaTest() {
t = new JTextArea(20, 50);
b = new JButton("Press me");
setLayout(new GridLayout(0, 1));
getContentPane().add(t);
getContentPane().add(b);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
test();
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
TextAreaTest f = new TextAreaTest();
f.pack();
f.show(); f.test2();
}
}
执行之后,明显发现,由test2()输出的B和C是分别输出的,而按下按钮后由test()输出的B和C是一起输出的。
我想在test()中得到test2()中的效果,请问这个问题应该怎么处理?
import java.awt.GridLayout;
import java.awt.event.*;import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;public class TextAreaTest extends JFrame {
private JTextArea t;
private JButton b;
private void test() {
t.append("B\n");
try {
Thread.sleep(2000);
}
catch (Exception ex) {}
t.append("C\n");
}
public void test2() {
t.append("B\n");
try {
Thread.sleep(2000);
}
catch (Exception ex) {}
t.append("C\n");
}
public TextAreaTest() {
t = new JTextArea(20, 50);
b = new JButton("Press me");
setLayout(new GridLayout(0, 1));
getContentPane().add(t);
getContentPane().add(b);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
test();
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
TextAreaTest f = new TextAreaTest();
f.pack();
f.show(); f.test2();
}
}
执行之后,明显发现,由test2()输出的B和C是分别输出的,而按下按钮后由test()输出的B和C是一起输出的。
我想在test()中得到test2()中的效果,请问这个问题应该怎么处理?
的时候ui是不会更新的。。主线程被锁定了 所以test才会出现一起输出的情况...
要么用多线程ms没必要
个人倾向用Timer
回2楼:test()和test2()是完全一样的方法,怎么效果不一样?照你说的,应该都被锁定才对啊。还是我没明白你的意思?
t.append("B\n");
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
} catch (Exception ex) {
}
t.append("C\n");
}
});
}
catch (Exception e) {
}
}
t.append("B\n");
t.paintImmediately(t.getBounds());
try {
Thread.sleep(1000);
} catch (Exception ex) {
}
t.append("C\n");
}