-2

I am new to JavaFx and to using filechooser on a current stage to get the file name and path to a file.

I have created test code to show the problem I am having...

test_main.java

package view;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;


public class test_main extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("/view/Sample.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

Here is my sample.fxml page that is in the same View package:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane fx:id="sample_page" prefHeight="681.0" prefWidth="503.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="view.SampleController">
  <children>

      <Button fx:id="btn_import_file" layoutX="403.0" layoutY="532.0" mnemonicParsing="false" text="Import File" />
  </children>
</AnchorPane>

Here is my SampleController.java class:

package view;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage; 
import javafx.stage.FileChooser;
import java.io.File;



public class SampleController implements Initializable {



    @FXML
    private AnchorPane samplePage;

    @FXML
    private Button btn_test_dialog;
    //this tests the operation of the alert dialog

   //private Stage export_chooser_stage;


    @FXML
    private Button export_posts_all;
    // this tests the file path select


    @FXML
    private Button btnImportFile;
    // this tests the import file path and name.





    //===================================================================================================================
    /*
     * This method will initialiise the UI
     */

    @Override
    public void initialize(URL url, ResourceBundle rb) 
    {
        //--------------------------------------------------------------------------------------------------------------------
        /*
         * This  is the  btn_import_file.setOnAction((event)
         */
        btnImportFile.setOnAction((event) -> 
        {
            Stage primaryStage=(Stage) samplePage.getScene().getWindow();
            //Stage primaryStage=new Stage();
            primaryStage.setTitle("JavaFX App");

            FileChooser fileChooser = new FileChooser();

            Button button = new Button("Select File");
            button.setOnAction(e -> {
                File selectedFile = fileChooser.showOpenDialog(primaryStage);
                String FileNamePath=selectedFile.toString();
                System.out.println("File name and path to file :"+FileNamePath); 
            });

            //VBox vBox = new VBox(button);
            //Scene scene = new Scene(vBox, 960, 600);

            //primaryStage.setScene(sample_page.getScene());
            primaryStage.getScene();
            primaryStage.show();
        });
        // this closes the  btn_test_dialog.setOnAction((event) ->  event


    }// close public void initialize(URL url, ResourceBundle rb)     



}// close public class SampleController implements Initializable 

What happens is:

1.the page loads and displays the button "Import file"

  1. When one onClick's "Import file" nothing happens.

The expected behaviour when onClicking "Import file" should be:

  1. The operating system file choose dialog should appear above the same stage as the "Import file" button. Selecting a file and path should print the File name and path to file : in the console.

  2. Clearly there is a problem in my code because I am a newbie to Java FX.

Would some-one be able to help me?

  • 1
    Need a minimal reproducible example... doesn't run, your `fx:id` tags don't match what's in the controller... you really need to follow Java naming conventions if you want people to be willing to take the time to help you. Files/Classes should be Capitalized without _underscores. methods/fields/properties should be camelCase without _underscores – b3tuning Jun 20 '20 at 07:50
  • Why are you creating a new button when “Import File” is pressed? You never display that button, so the user never has the opportunity to press it, and so it’s handler (which opens the file chooser) can never be executed. Just show the file chooser directly in the “Import File” button handler. – James_D Jun 20 '20 at 12:54
  • Thank you for this, but I do agree with Jame_D as to why I need to create another button as it confuses me... but although I am prototyping it with a button action, on the actual application this fileChooser is actual being intiated from a menu item... how do I recode this control class for menu item, without a adding a button? – Flash Jack From Gundagai Jun 20 '20 at 16:21

1 Answers1

1

fix your Sample.fxml file so the fx:id matches what's in the controller... change this:

<AnchorPane fx:id="sample_page" prefHeight="681.0" prefWidth="503.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="view.SampleController">
  <children>

      <Button fx:id="btn_import_file" layoutX="403.0" layoutY="532.0" mnemonicParsing="false" text="Import File" />

to this:

<AnchorPane fx:id="samplePage" prefHeight="681.0" prefWidth="503.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="view.SampleController">
  <children>

      <Button fx:id="btnImportFile" layoutX="403.0" layoutY="532.0" mnemonicParsing="false" text="Import File" />

In your controller, you never add the new button to the view, so you'll never hit its ActionEvent

Modify your controller like so,

        btnImportFile.setOnAction((event) -> {
            // Get the window for the current view to pass to the
            // FileChooser showOpenDialog()
            Window      primaryStage = samplePage.getScene().getWindow();
            FileChooser fileChooser  = new FileChooser();

            Button button = new Button("Select File");
            // Add your new button to this view
            // What will you do with this button after?  How will you dispose of it?
            samplePage.getChildren().add(button);
            button.setOnAction(e -> {
                File   selectedFile = fileChooser.showOpenDialog(primaryStage);

                // This will NPE if user cancels showOpenDialog.. 
                // and shpuld be `fileNamePath`
                // and I think you want `selectedFile.getPath()`
                // or `selectedFile.getAbsolutePath()`
                String FileNamePath = selectedFile.toString();
                System.out.println("File name and path to file :" + FileNamePath);
            });
        });
b3tuning
  • 337
  • 2
  • 8