I'm trying to code the functionality of a button created using SceneBuilder. I found the "Code" section in Scene builder and set the name of the method that will launch when I click on the button (e.g. fileSelector). In the method I should use FileChooser variable(I need to take an image from the PC and save it to a "File" variable).
I copied the sample controller skeleton and paste it to my Controller class. Now I don't know how to implement the method, because I need a Stage variable to use with the FileChooser variable, but the stage variable is given for the public void start(Stage primaryStage)
method.
My Main Class
package application;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
public class MainExample extends Application {
@Override
public void start(Stage primaryStage) throws IOException {
Pane firstPane = FXMLLoader.load(MainExample.class.getClassLoader().getResource("buttonExample.fxml"));
Scene firstScene = new Scene(firstPane);
primaryStage.setScene(firstScene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
My Controller Class
package application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
public class MyController {
@FXML
private Button selectFile;
@FXML
void fileSelector(ActionEvent event) {
FileChooser fileChooser = new FileChooser();
File file = fileChooser.showOpenDialog(stage);
}
}
The FXML from the button
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.Pane?>
<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="135.0" prefWidth="280.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MyController">
<children>
<Button fx:id="selectFile" layoutX="102.0" layoutY="55.0" mnemonicParsing="false" onAction="#fileSelector" text="SelectFile" />
</children>
</Pane>