0

这个问题包含我之前的问题的代码

主班

    @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`
4

1 回答 1

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;

SSCCE

示例.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 }   
}

应用程序.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);  }
}
于 2013-05-22T17:57:11.537 回答