Is there a method similar to getSelectedFile
in JavaFX that returns a File
? I have tried this code now trying to perfect the commented out //fileToSend[0]
@FXML
private void chooseButtonAction(ActionEvent event) throws IOException {
FileChooser JFileChooser = new FileChooser();
JFileChooser.setTitle("Choose a file to send");
Stage stage = (Stage) anchorPane.getScene().getWindow();
File file = JFileChooser.showOpenDialog(stage);
if (file != null) {
//fileToSend[0] = JFileChooser.getSelectedFile();
fileName.setText("File Name " file.getName());
}
}
CodePudding user response:
import java.io.File;
import java.util.List;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
/** @see https://stackoverflow.com/a/71362723/230513 */
public class FileChooserDemo extends Application {
private static final int PADDING = 16;
@Override
public void start(Stage stage) {
stage.setTitle("FileChooserDemo");
FileChooser fileChooser = new FileChooser();
Label label = new Label("Select one or more files:");
TextArea textArea = new TextArea();
textArea.setPrefColumnCount(16);
textArea.setPrefRowCount(4);
Button singleButton = new Button("Select a File");
singleButton.setOnAction((ActionEvent t) -> {
File file = fileChooser.showOpenDialog(stage);
if (file != null) {
textArea.clear();
textArea.appendText(file.getName());
}
});
Button multiButton = new Button("Select Files");
multiButton.setOnAction((ActionEvent t) -> {
List<File> selected = fileChooser.showOpenMultipleDialog(stage);
if (selected != null) {
textArea.clear();
selected.forEach(file -> textArea.appendText(file.getName() "\n"));
}
});
VBox vBox = new VBox(PADDING, label, singleButton, multiButton, textArea);
vBox.setAlignment(Pos.CENTER);
vBox.setPadding(new Insets(PADDING));
Scene scene = new Scene(vBox);
stage.setScene(scene);
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}