如何使用来自另一个类(不是来自另一个场景,而是来自另一个类!)的控制器的元素(标签、TextView 等)
假设我不想在 Controller 中工作,因为它不方便。我准备了一个小项目,我有一个场景,当单击一个按钮时,它会在 Controllere 中读取此单击并将处理转移到另一个 Test.java 类,其中有一个 test() 方法,它会更改LabelTest("Тест")
为("Тест прошёл успешно")
. 但出现错误NullPointerException
。
编码:
package application;
import javax.print.DocFlavor.URL;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
java.net.URL fxmlURL = getClass().getResource("xmlFiles/oneOkon.fxml");
Parent root = FXMLLoader.load(fxmlURL);
Scene scene = new Scene(root);
primaryStage.setTitle("Hello world");
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
package application;
import javafx.fxml.FXML;
import javafx.event.ActionEvent;
import javafx.scene.control.Label;
public class MainController {
@FXML
private Label LabelTest;
public Label getLabelTest() {
return LabelTest;
}
@FXML
public void buttonTest(ActionEvent event) {
Test.test();
}
}
package application;
public class Test {
public static void test() {
MainController t = new MainController();
t.getLabelTest().setText("Тест прошёл успешно");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.text.Font?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MainController">
<top>
<Label fx:id="LabelTest" prefHeight="76.0" prefWidth="503.0" text="Тест" BorderPane.alignment="CENTER">
<font>
<Font size="30.0" />
</font>
</Label>
</top>
<center>
<Button mnemonicParsing="false" onAction="#buttonTest" prefHeight="187.0" prefWidth="526.0" text="Проверка" BorderPane.alignment="CENTER" />
</center>
</BorderPane>