当用户单击“保存”按钮时,我正在尝试使用SaveUtil打开FileChooser。 FileChooser需要访问舞台。
您将如何做?
SaveUtil
public class SaveUtil {
public static void saveCanvas(){
FileChooser fileChooser = new FileChooser();
//Set extension filter
FileChooser.ExtensionFilter extFilter =
new FileChooser.ExtensionFilter("png files (*.png)", "*.png");
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File file = fileChooser.showSaveDialog(primaryStage);
if(file != null){
try {
WritableImage writableImage = new WritableImage(CANVAS_WIDTH, CANVAS_HEIGHT);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
控制器按钮定义:
@FXML
private Canvas fractal; // This is a drawable area
@FXML
private void saveCanvas(){
SaveUtil.saveCanvas();
}
ui.fxml
<Button text="Save" mnemonicParsing="false" onAction="#saveCanvas"/>
主要
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception{
String mainwindow = "/fxml/ui.fxml";
Parent root = null;
URL mainwindowUrl = null;
try {
mainwindowUrl = getClass().getResource(mainwindow);
root = FXMLLoader.load(mainwindowUrl);
System.out.println(" mainwindow = " + mainwindow);
}catch (Exception ex){
System.out.println( "Exception on FXMLLoader.load()" );
System.out.println( " * url: " + mainwindowUrl );
System.out.println( " * " + ex );
System.out.println( " ----------------------------------------\n" );
throw ex;
}
// Parent root = FXMLLoader.load(getClass().getResource("fxml/ui.fxml"));
primaryStage.setTitle("Fractal Friend");
primaryStage.setScene(new Scene(root, 1200, 700));
primaryStage.show();
}
}