X
X
XOM91K2021-10-31 20:21:18
Java
XOM91K, 2021-10-31 20:21:18

How to pass Class1 variables to Class2 if in Class1 they are associated with FXML?

the .fxml file has a Text object with its own fx:id

<Text fx:id="system_messages" layoutX="202.0" layoutY="638.0" strokeType="OUTSIDE" strokeWidth="0.0" text="сообщений пока нет..." wrappingWidth="889.69921875">

in the main controller I declared this object with the same name as fx:id.
public class MainController implements Initializable {
    @FXML
    Text system_messages;
...

Now I need to change the text of the system_messages object , for example to "An error occurred", but not in the MainController but in another class, for example in the SystemMessagesController class in a dedicated controller that will change the textbox texts ... I'm trying to do it like this:
public class SystemMessagesController {
    MainController main = new MainController();
    
    public void system_messages(String type) {
        switch (type) {
            case "UnknownHostException": {
                FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("main.fxml"));
                main = (MainController) fxmlLoader.getController ();
                main.system_messages.setText("Ошибка получения данных. Проверьте подключение к интернету.");
            }
            default: {
                main.system_messages.setText("Ошибка получения данных. Ошибка неизвестна.");
            }
        }
    }
}

But an error occurs
Caused by: java.lang.NullPointerException: Cannot read field "system_messages" because "this.main" is null

I understand it has something to do with @FXML before declaring the System_messages Text object; but I don't have enough knowledge to understand how it can be fixed... Still, I would like not to litter in the main controller, but to do it in the second one... Help please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Chesterfield25, 2021-11-01
@Chesterfield25

You are getting an error in the SystemMessagesController class with a value nullfor the reason that yours system_messagesis in another class, namely MainController.
You need to pass system_messagesfrom the MainController class to the SystemMessagesController class! And in the class itself, get system_messagesand substitute in replacements for the text of the message. And also in yours main.fxmlshould be

<Text fx:id="get_system_messages" layoutX="202.0" layoutY="638.0" strokeType="OUTSIDE" strokeWidth="0.0" text="сообщений пока нет..." wrappingWidth="889.69921875">

Should be something like this
main.get_system_messages.setText("сюда передаём system_messages");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question