Search code examples
javamultithreadingevent-dispatch-threadswingutilities

Updating a textfield using SwingUtilities.invokeLater()


My program consists of a simple gui and a class that extends thread!

i am trying to learn how to use SwingUtilities.invokeLater() in order to use it to update a textfield in my GUI but how do i reach the textfield in my gui without making static? and am i on the right track or have i done something wrong so far:)?

Code

This has been taken from the Class called Client that extends thread this is where i want to update my GUI from using SwingUtilities.invokeLater(Runnable)

public void run(){
    while (socket.isConnected()) {

    if (input.hasNext()) {

        updateTextField();
    }

}
}

private void updateTextField() {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
  // here i want to update my textfield using txt.setText(input.nextLine());

        }
    });

}

UPDATE (This is my code so far) getting a nullpointer execption

public void run(){
    while (socket.isConnected()) {
            String x = input.next();
            System.out.println(x);
    mg.updateChat(x); // this is the line that gives me the nullexeption

    }
}

in my GUI

public void updateChat(final String input){
SwingUtilities.invokeLater(new Runnable() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
    txtChat.setText(input); 
    }
}); 
}

Solution

  • You can do it by having a final local variable in the method that contains the call to invokeLater(). You can access that variable from within the runnable object.

    For example:

    public void run(){
      while (socket.isConnected()) {
        if (input.hasNext()) {
          String nextInput = input.next();
          myGui.updateTextField(nextInput);
        }
      }
    }
    

    in your GUI class:

    public void updateTextField(final String nextInput) {
      SwingUtilities.invokeLater(
        new Runnable(){
          @Override
          public void run() {
            // assuming a private JTextField variable, myTextField
            myTextField.setText(nextInput);
          }
        }
      );
    }