在我在 textarea 中显示文本的函数中,我编写了以下代码行,但它没有显示任何文本
jTextArea1.setText( Packet +"\n" +jTextArea1.getText());
我正在使用 swingworker 执行后台任务,这是我的代码
public class SaveTraffic extends SwingWorker<Void, Void> {
public GUI f = new GUI();
@Override
public Void doInBackground() throws IOException {
//some code
sendPacket(captor.getPacket().toString());
return null;
}//end main function
@Override
public void done() {
System.out.println("I am DONE");
}
public void sendPacket(String Packet) {
f.showPackets(Packet);
}
}
以及我在我的 GUI 表单中编写的以下代码行
public void showPackets(String Packet) {
jTextArea1.append( Packet);
}
解决方案:公共类 SaveTraffic 扩展 SwingWorker {
public GUI f = new GUI();
@Override
public Void doInBackground() throws IOException {
f.add(jTextPane1);
// some code
publish(captor.getPacket().toString());
// the method below is calling sendPacket on the background thread
// which then calls showPackets on the background thread
// which then appends text into the JTextArea on the background thread
//sendPacket(captor.getPacket().toString());
return null;
}
@Override
protected void process(List<String> chunks) {
for (String text : chunks) {
jTextPane1.setText(text);
f.showPackets(text);
}
}
@Override
public void done() {
System.out.println("I am DONE");
}
}