Xar*_*ara 4 java swing swingworker jtextarea
在我在textarea中显示文本的功能中,我编写了以下代码行,但它没有显示任何文本
jTextArea1.setText( Packet +"\n" +jTextArea1.getText());
Run Code Online (Sandbox Code Playgroud)
我正在使用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);
}
Run Code Online (Sandbox Code Playgroud)
}
以及我用GUI表单编写的以下代码行
public void showPackets(String Packet) {
jTextArea1.append( Packet);
}
Run Code Online (Sandbox Code Playgroud)
解决方案:公共类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");
}
Run Code Online (Sandbox Code Playgroud)
}
你的问题是一个非常不完整的问题,一个没有足够信息来提供答案的问题,以及一个迫使我们猜测的问题,但是基于原始帖子中的这一行:
该功能被连续调用......
我猜,我会打赌,你有一个Swing线程问题.您可能希望阅读并使用SwingWorker.
从这里开始了解EDT和SwingWorkers:Swing中的并发性.
是的,你的是由后台线程中的Swing调用引起的Swing并发问题.为避免这样做,您需要从doInBackground导出数据并在Swing事件线程上调用它.一种方法是通过发布/处理方法对:
public class SaveTraffic extends SwingWorker<Void, String> {
public GUI f = new GUI();
@Override
public Void doInBackground() throws IOException {
// 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> packetTextList) {
for (String packetText : packetTextList) {
sendPacket(packetText); //edit, changed to match your code
}
}
@Override
public void done() {
System.out.println("I am DONE");
}
public void sendPacket(String Packet) {
f.showPackets(Packet);
}
}
Run Code Online (Sandbox Code Playgroud)
查看我上面链接的教程和SwingWorker API以获取更多详细信息.