Last active
November 13, 2017 04:47
-
-
Save momolinus/5f695cb423c27e44e042844ccc8c7dde to your computer and use it in GitHub Desktop.
how to use Optional if any API interface returns null indicating missing value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.util.Optional; | |
import javafx.application.Application; | |
import javafx.event.ActionEvent; | |
import javafx.scene.Scene; | |
import javafx.scene.control.Button; | |
import javafx.scene.layout.FlowPane; | |
import javafx.stage.FileChooser; | |
import javafx.stage.Stage; | |
/** | |
* @author Marcus Bleil, http://www.marcusbleil.de | |
*/ | |
public class FileChooserDemo extends Application { | |
private FileChooser fileChooser; | |
@Override | |
public void start(Stage primaryStage) { | |
fileChooser = new FileChooser(); | |
FlowPane root = new FlowPane(); | |
Button fileOpenButton = new Button("file open..."); | |
fileOpenButton.setOnAction(this::fileChooserButtonEvent); | |
root.getChildren().add(fileOpenButton); | |
Scene scene = new Scene(root, 400, 300); | |
primaryStage.setScene(scene); | |
primaryStage.setTitle("FileChooser with Optional Demo"); | |
primaryStage.show(); | |
} | |
private void fileChooserButtonEvent(ActionEvent event) { | |
Optional<File> selectedFile = Optional.ofNullable(fileChooser.showOpenDialog(null)); | |
if (selectedFile.isPresent()) { | |
System.out.println("selected: " + selectedFile.get().getAbsolutePath()); | |
} | |
else { | |
System.out.println("file seletion canceled by user"); | |
} | |
} | |
public static void main(String[] args) { | |
launch(args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment