2013-06-22 81 views
0

我在这里是新来的,我是Java编程的新手,但是我不得不报名参加这个问题,因为它让我困扰了好几天。 无论如何,我正在写TCP客户端。我做了两个线程:一个用于从System.in读取并发送到套接字,另一个用于从套接字读取并写入System.out。 这工作得很好,但现在我需要做一个GUI,我知道如果我想保持我的GUI交互,我需要使用任务和/或服务,但我不知道如何使我的线程作为服务。 这里的代码(即在终端工作):JavaFX GUI卡住

public static class ReadThread extends Thread 
{ 
    BufferedReader in; 
    String word; 

    ReadThread(BufferedReader in) 
    { 
     this.in = in; 
    } 

    @Override 
    public void run() 
    { 
     try { 
      while((word = in.readLine()) != null) 
       System.out.println(word); 
     } catch (IOException ex) { 
      Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
} 

与此类似,我做了WriteThread,但我不想让这个帖子凌乱所以...... 无论如何,当我试图实现这个作为服务,我不得不在“最终”中产生一些其他错误,如此等等。 我会很感激,如果你能帮我在我的特定情况下,因为我可能读这个网站上的所有JavaFX的GUI问题haha 在此先感谢和抱歉的长篇文章! :d

回答

1

我这是怎么实现的服务

public class ReadService extends Service { 

    BufferedReader in; 
    String word; 

    @Override 
    protected Task createTask() { 
     return new Task() { 
      @Override 
      protected Object call() throws Exception { 
       try { 
        while((word = in.readLine()) != null) 
         System.out.println(word); 
       } catch (IOException ex) { 
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); 
       } 
       return null; 
      } 
     }; 
    } 

    public BufferedReader getIn() { 
     return in; 
    } 

    public void setIn(BufferedReader in) { 
     this.in = in; 
    } 
} 

而且,你必须打电话给你的服务。

ReadService readService = new ReadService(); 
     readService.setIn(//HEre your in); 
      readService.restart(); 

您还可以添加一些处理程序时,您的服务启动,取消,失败,完成...

readService.setOnSucceeded(new EventHandler<WorkerStateEvent>() { 
     @Override 
     public void handle(WorkerStateEvent workerStateEvent) { 
      // Here the finish action 
     } 
    }); 

那它

+0

非常感谢!有用!但现在我必须从textField和textArea中取代并设置System.in和System.out。 我实际上使它从System.in读取并写入textArea,但我不知道如何从textField获取文本。我不想一直使用发送按钮,而且我也不知道如何将一个事件方法发送到服务类。 任何想法? – Bade

+0

在TextField或TextArea中,您可以在textfield的textProperty()上添加一个eventListener,并在文本更改时调用它。或者你可以只为textfield.getText() –

+0

但我应该.start()新的writeService任务与文本上的每个新事件改变或我可以以某种方式传递一个方法writeService? 对不起,但我觉得很容易混淆变量范围的原因:( 最让我困惑的是这两行: 'while((command = in.readLine())!= null) out.println(naredba) ;'。我无法编写command = textField.getText();导致它不知道何时获取文本 对不起,因为在颈部疼痛,但我需要做到这一点:D – Bade