为什么我的textArea不能实时工作?

时间:2013-08-07 16:38:56

标签: java swing user-interface while-loop jtextarea

我正在尝试追加我从客户端程序中获取的字符串。但是我这样做是为了使append语句处于while循环中。这对不能实时工作有影响吗?

适用于

等领域
   tfFIXMsg.append( inputLine + "\n\n\n");

       tfCSVLine.append(outputLine+"\n\n\n");

它不会在textArea上显示消息UNTIL完成while循环。 我怎样才能使它继续接收来自客户端的消息,并能够实时将其输出到textArea

try {
    while ((inputLine = in.readLine()) != null) 
          { 
           System.out.println ("Server: " + inputLine); 


           tfFIXMsg.append( inputLine + "\n\n\n");


           int pos = inputLine.indexOf(inputLine, 0);
           h.addHighlight(50, 60, DefaultHighlighter.DefaultPainter);



           if (inputLine.trim().equals("Bye.")) {
               System.out.println("Exit program"); 
               break;
               } 

           Scanner input1 = new Scanner(new File(csvName));
           Scanner input2 = new Scanner(new File(csvName));
           Scanner input3 = new Scanner(new File(csvName));
           Scanner input4 = new Scanner(new File(csvName));


           String csvline = getCsvLineVal (getLocation34CSV(getTag34Value(Tag34Location(getTagCSV( parseFixMsg(inputLine ,inputLine))), getValueCSV( parseFixMsg(inputLine ,inputLine))), getVal34(input1,  input2)), getCSVLine( input3,  input4) );
           outputLine = compareClientFixCSV( getTagCSV( parseFixMsg(inputLine ,inputLine)), getValueCSV(parseFixMsg(inputLine ,inputLine)), getCSVTag(csvline), getCSVValue(csvline));

           out.println(outputLine);
           tfCSVLine.append(outputLine+"\n\n\n");

           input1.close();
           input2.close();
           input3.close();
           input4.close();



          }
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

2 个答案:

答案 0 :(得分:2)

如果您这样做,它们将在EDT(事件调度线程)中执行。您应该通过启动新的Thread将逻辑移到EDT之外,以允许Swing正确地重新绘制UI并将更新发布到UI,如下所示:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
      // Your Code Here
    }
});

另请考虑使用javax.swing.SwingWorkerjavax.swing.Timer并查看Concurrency in Swing

答案 1 :(得分:2)

我想,你的代码不在EDT线程上运行。如果它运行,你应该将它移动到另一个。

然后,您可以使用该其他线程来更新Swing UI元素:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        tfFIXMsg.append( inputLine + "\n\n\n");
        // or whatever swing action you want to perform...
    }
});

如果您需要更复杂的解决方案,请尝试使用SwingWorker类。