0

I'm building a lobby that should display messages from players.

Here is my lobby controller:

public class LobbyController{

    @FXML public JFXTextArea chatArea;
    @FXML public JFXTextField chatField;

    public void displayChatMessage(String message){
        chatArea.appendText(message);
    }

    @FXML
    public void onEnter(){
        Main.client.sendChatMessage(chatField.getText());
    }
}

I'm accessing this controller from another class like this:

FXMLLoader fxmlLoader = new FXMLLoader();                
fxmlLoader.setLocation(getClass().getResource("/views/lobby.fxml"));
fxmlLoader.load();
LobbyController controller = fxmlLoader.getController();

if(!gameStarted){
    controller.displayChatMessage(((Packets.ChatMessage) o).message);
}

My controller is definitely receiving the message as if I put a print line in displayChatMessage(), it prints the message correctly.

My problem is that appendText() does not seem to be changing the text at all.

Yahya
  • 13,349
  • 6
  • 30
  • 42
Jaden Wang
  • 126
  • 1
  • 9
  • You're not displaying the UI you load from the FXML file. What are you expecting to see when you call `controller.displayChatMessage()`? – James_D Jun 01 '17 at 21:09
  • I can get the fxml file to load properly such that I see everything that is intended. `displayChatMessage()` is supposed to append a new string to my text area that is already loaded. – Jaden Wang Jun 01 '17 at 21:14
  • You're missing my point. Your `lobby.fxml` file defines a UI. That UI has a text area in it (presumably among other things). When you call `fxmlloader.load()`, the FXML loader creates a new UI, including a new text area, and returns a reference to the root of the UI. The controller you get is the controller *for that UI*. Since you are not displaying that UI (you don't even assign it to a reference), you are updating a text area that is not displayed anywhere. If you have already loaded the FXML file *and displayed it*, you need the controller for *that UI*, not the one you don't display. – James_D Jun 01 '17 at 21:23
  • Sorry for being dumb, how would I do that? – Jaden Wang Jun 01 '17 at 21:30
  • At some point, you presumably load the fxml *and display it*. At that point, you need to get the controller, just the same way you in the code you posted in the question. Then arrange to call `displayChatMessage(...)` on that controller. – James_D Jun 01 '17 at 21:38
  • Thanks, I've managed to get it to work. However, I'm not sure if I'm doing it the best way or not. I just assigned a static controller variable to my Main application and referenced it from the other class. – Jaden Wang Jun 01 '17 at 22:07
  • Yeah, that's not necessarily the best way - it's probably better to pass the reference to the instance of the other class. But at least now you can see exactly what needs to be shared. – James_D Jun 01 '17 at 22:10

0 Answers0