在 JavaFX 中使用文件选择器查找文件然后将其路径另存为字符串
Using Filechooser in JavaFX to Find A File Then Save It's Path As A String
我想知道是否可以在 JavaFX 中使用文件选择器来定位文件,然后当我在文件选择器中单击 "open" 时,它会以某种方式将该文件的文件路径记录为字符串?
我在网上查看了如何执行此操作,但没有看到任何解释。如果有人可以向我展示一些如何执行此操作的示例代码,我将不胜感激:)
文件选择器returns一个文件:
File file = chooser.showOpenDialog(stage);
您只需对文件调用 toString()
即可将文件作为字符串值获取:
if (file != null) {
String fileAsString = file.toString();
. . .
}
示例应用程序
import javafx.application.Application;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
public class SavePath extends Application {
@Override
public void start(final Stage stage) throws Exception {
Button button = new Button("Choose");
Label chosen = new Label();
button.setOnAction(event -> {
FileChooser chooser = new FileChooser();
File file = chooser.showOpenDialog(stage);
if (file != null) {
String fileAsString = file.toString();
chosen.setText("Chosen: " + fileAsString);
} else {
chosen.setText(null);
}
});
VBox layout = new VBox(10, button, chosen);
layout.setMinWidth(400);
layout.setAlignment(Pos.CENTER);
layout.setPadding(new Insets(10));
stage.setScene(new Scene(layout));
stage.show();
}
public static void main(String[] args) throws Exception {
launch(args);
}
}
我想知道是否可以在 JavaFX 中使用文件选择器来定位文件,然后当我在文件选择器中单击 "open" 时,它会以某种方式将该文件的文件路径记录为字符串?
我在网上查看了如何执行此操作,但没有看到任何解释。如果有人可以向我展示一些如何执行此操作的示例代码,我将不胜感激:)
文件选择器returns一个文件:
File file = chooser.showOpenDialog(stage);
您只需对文件调用 toString()
即可将文件作为字符串值获取:
if (file != null) {
String fileAsString = file.toString();
. . .
}
示例应用程序
import javafx.application.Application;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
public class SavePath extends Application {
@Override
public void start(final Stage stage) throws Exception {
Button button = new Button("Choose");
Label chosen = new Label();
button.setOnAction(event -> {
FileChooser chooser = new FileChooser();
File file = chooser.showOpenDialog(stage);
if (file != null) {
String fileAsString = file.toString();
chosen.setText("Chosen: " + fileAsString);
} else {
chosen.setText(null);
}
});
VBox layout = new VBox(10, button, chosen);
layout.setMinWidth(400);
layout.setAlignment(Pos.CENTER);
layout.setPadding(new Insets(10));
stage.setScene(new Scene(layout));
stage.show();
}
public static void main(String[] args) throws Exception {
launch(args);
}
}