此问题包含我之前的question
的代码主要课程
@Override
public void start(Stage mainStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLfile.fxml"));
Scene scene = new Scene(root);
scene.setFill(Color.TRANSPARENT);
stage.initStyle(StageStyle.TRANSPARENT);
stage.setScene(scene);
stage.show();
}
FXMLController类
@FXML
private void getAxisLoc(ActionEvent axis) {
Stage stage;
stage = (Stage) root.getScene().getWindow();
int locX;
locX = (int) stage.getX();
int locY;
locY = (int) stage.getY();
}
这里引发了异常:
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:279)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1435)
... 48 more
Caused by: java.lang.NullPointerException
at myJavaFile.FXMLfileController.getAxisLoc(FXMLfileController.java:112)
... 58 more`
答案 0 :(得分:4)
盲目地,我想在这里解雇了NullPointerExeption
:
stage = (Stage) root.getScene().getWindow();
如果是这样,请确保在根窗格标记中添加了fx:id="root"
。
示例(FXML):
<BorderPane fx:id="root" xmlns:fx="http://javafx.com/fxml" fx:controller="YourController">
并在controller
课程中引用它:
@FXML
Parent root;
<强> Sample.fxml 强>
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" fx:id="root" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="SampleController">
<children>
<Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" />
<Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" />
</children>
</AnchorPane>
<强> SampleController.java 强>
public class SampleController implements Initializable {
@FXML
private Label label;
@FXML
private Pane root;
@FXML
private void handleButtonAction(ActionEvent event) {
Stage stage = (Stage) root.getScene().getWindow();
//you can use label instead of root.
//Stage stage= (Stage) label.getScence().getWindow();
stage.close();
}
@Override
public void initialize(URL url, ResourceBundle rb) { //TODO }
}
<强> App.java 强>
public class App extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) { launch(args); }
}