Java Code Examples for javafx.stage.FileChooser#setInitialFileName()

The following examples show how to use javafx.stage.FileChooser#setInitialFileName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestCollectionController.java    From pmd-designer with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void importTestsFromFile() {
    FileChooser chooser = new FileChooser();
    File origin = getTestCollection().getOrigin();
    chooser.setInitialFileName(origin == null ? null : origin.getAbsolutePath());
    chooser.setTitle("Load source from file");
    File file = chooser.showOpenDialog(getMainStage());

    if (file == null) {
        SimplePopups.showActionFeedback(addTestMenuButton, AlertType.INFORMATION, "No file chosen");
        return;
    }

    try {
        TestCollection coll = TestXmlParser.parseXmlTests(file.toPath(), builder);
        getTestCollection().addAll(coll);
        getTestCollection().setOrigin(file);
        SimplePopups.showActionFeedback(addTestMenuButton, AlertType.CONFIRMATION,
                                        "Imported " + coll.getStash().size() + " test cases");
    } catch (Exception e) {
        SimplePopups.showActionFeedback(addTestMenuButton, AlertType.ERROR, "Error while importing, see event log");
        logUserException(e, Category.TEST_LOADING_EXCEPTION);
    }
}
 
Example 2
Source File: EditorMainWindow.java    From metastone with GNU General Public License v2.0 6 votes vote down vote up
private void save() {
	FileChooser fileChooser = new FileChooser();
	fileChooser.setTitle("Save card");
	fileChooser.setInitialDirectory(new File("./cards/"));
	fileChooser.setInitialFileName(card.id + ".json");
	File file = fileChooser.showSaveDialog(getScene().getWindow());
	if (file == null) {
		return;
	}
	System.out.println("Saving to: " + file.getName());
	GsonBuilder builder = new GsonBuilder().setPrettyPrinting();
	builder.disableHtmlEscaping();
	builder.registerTypeAdapter(SpellDesc.class, new SpellDescSerializer());
	Gson gson = builder.create();
	String json = gson.toJson(card);
	try {
		// FileUtils.writeStringToFile(file, json);
		Path path = Paths.get(file.getPath());
		Files.write(path, json.getBytes());
		Desktop.getDesktop().open(file);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 3
Source File: Controller.java    From PoE_Level_Buddy with MIT License 6 votes vote down vote up
/**
 * File Browser for Client.txt
 */
public void browseFiles()
{
    FileChooser fileChooser = new FileChooser();
    fileChooser.setInitialFileName("Client.txt");
    fileChooser.setTitle("Select PoE's Client.txt File");
    fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Client.txt", "Client.txt"));
    File selectedFile = fileChooser.showOpenDialog(null);

    if (selectedFile != null)
    {
        Settings.getINSTANCE().setClientTXT(selectedFile);
        Platform.runLater(() -> clientPATH.setText(selectedFile.getAbsolutePath()));
        // I'm going to trust the FileChooser that the file exists.
        errorNoClientTxt.setVisible(false);
    }
}
 
Example 4
Source File: ImportWizardView1Controller.java    From pikatimer with GNU General Public License v3.0 6 votes vote down vote up
@FXML
protected void chooseFile(ActionEvent fxevent){
    
    final FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Open CSV File");
    
    if (model.getFileName().equals("")) {
        fileChooser.setInitialDirectory(PikaPreferences.getInstance().getCWD());
    } else {
        fileChooser.setInitialFileName(model.getFileName()); 
    }
    fileChooser.getExtensionFilters().addAll(
            new FileChooser.ExtensionFilter("CSV/TXT Files", "*.csv", "*.txt"),
            new FileChooser.ExtensionFilter("All files", "*")
        );
    File file = fileChooser.showOpenDialog(fileChooserButton.getScene().getWindow());
    if (file != null && file.exists() && file.isFile() && file.canRead()) {
       // model.setFileName(file.getAbsolutePath());
        fileTextField.setText(file.getAbsolutePath());
        //model.nextButtonDisabledProperty().set(false);
    }        
}
 
Example 5
Source File: SpellsKnownTab.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Select a spell output sheet
 */
private void selectSpellSheetButton()
{
	FileChooser fileChooser = new FileChooser();
	fileChooser.setTitle(LanguageBundle.getString("InfoSpells.select.output.sheet"));
	fileChooser.setInitialDirectory(new File(ConfigurationSettings.getOutputSheetsDir()));
	if (PCGenSettings.getSelectedSpellSheet() != null)
	{
		fileChooser.setInitialFileName(PCGenSettings.getSelectedSpellSheet());
	}
	File selectedFile = fileChooser.showOpenDialog(null);

	if (selectedFile != null)
	{
		PCGenSettings.getInstance().setProperty(PCGenSettings.SELECTED_SPELL_SHEET_PATH,
			selectedFile.getAbsolutePath());
		spellSheetField.setText(selectedFile.getName());
		spellSheetField.setToolTipText(selectedFile.getName());
	}
}
 
Example 6
Source File: IliasPdfDownloadCaller.java    From iliasDownloaderTool with GNU General Public License v2.0 6 votes vote down vote up
private void askForStoragePosition(String name, final String targetPath, final IliasFile file) {
	final FileChooser fileChooser = new FileChooser();
	fileChooser.setInitialDirectory(new File(targetPath));
	fileChooser.setInitialFileName(name + "." + file.getExtension());

	Platform.runLater(new Runnable() {
		@Override
		public void run() {
			final File selectedFile = fileChooser.showSaveDialog(new Stage());
			String path = targetPath;
			if (selectedFile != null) {
				path = selectedFile.getAbsolutePath();
				if (!path.endsWith("." + file.getExtension())) {
					path = path + "." + file.getExtension();
				}
				new Thread(new IliasFileDownloaderTask(file, path)).start();
			}
		}
	});
}
 
Example 7
Source File: ChatView.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
private void onOpenAttachment(Attachment attachment) {
    if (!allowAttachments)
        return;
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle(Res.get("support.save"));
    fileChooser.setInitialFileName(attachment.getFileName());
   /* if (Utilities.isUnix())
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));*/
    File file = fileChooser.showSaveDialog(getScene().getWindow());
    if (file != null) {
        try (FileOutputStream fileOutputStream = new FileOutputStream(file.getAbsolutePath())) {
            fileOutputStream.write(attachment.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
}
 
Example 8
Source File: Tools.java    From logbook-kai with MIT License 6 votes vote down vote up
/**
 * テーブルの内容をCSVファイルとして出力します
 *
 * @param table テーブル
 * @param title タイトル及びファイル名
 * @param own 親ウインドウ
 */
public static void store(TableView<?> table, String title, Window own) throws IOException {
    String body = table.getItems()
            .stream()
            .map(Object::toString)
            .collect(Collectors.joining(CSV_NL))
            .replaceAll(SEPARATOR, CSV_SEPARATOR);
    String content = new StringJoiner(CSV_NL)
            .add(tableHeader(table, CSV_SEPARATOR))
            .add(body)
            .toString();

    FileChooser chooser = new FileChooser();
    chooser.setTitle(title + "の保存");
    chooser.setInitialFileName(title + ".csv");
    chooser.getExtensionFilters().addAll(
            new ExtensionFilter("CSV Files", "*.csv"));
    File f = chooser.showSaveDialog(own);
    if (f != null) {
        Files.write(f.toPath(), content.getBytes(LogWriter.DEFAULT_CHARSET));
    }
}
 
Example 9
Source File: Controller.java    From xdat_editor with MIT License 6 votes vote down vote up
@FXML
private void saveAs() {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Save script");
    if (scriptFile != null)
        fileChooser.setInitialFileName(scriptFile.getName());

    if (initialDirectory != null)
        fileChooser.setInitialDirectory(initialDirectory);

    File file = fileChooser.showSaveDialog(editor.getStage());
    if (file == null)
        return;

    this.scriptFile = file;
    initialDirectory = file.getParentFile();

    save();
}
 
Example 10
Source File: Controller.java    From xdat_editor with MIT License 6 votes vote down vote up
@FXML
private void saveAs() {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Save");
    fileChooser.getExtensionFilters().addAll(
            new FileChooser.ExtensionFilter("XDAT (*.xdat)", "*.xdat"),
            new FileChooser.ExtensionFilter("All files", "*.*"));
    fileChooser.setInitialFileName(xdatFile.getValue().getName());

    if (initialDirectory.getValue() != null &&
            initialDirectory.getValue().exists() &&
            initialDirectory.getValue().isDirectory())
        fileChooser.setInitialDirectory(initialDirectory.getValue());

    File file = fileChooser.showSaveDialog(editor.getStage());
    if (file == null)
        return;

    this.xdatFile.setValue(file);
    initialDirectory.setValue(file.getParentFile());

    save();
}
 
Example 11
Source File: CreatePacFileController.java    From logbook-kai with MIT License 5 votes vote down vote up
@FXML
void save(ActionEvent event) {
    try {
        String packFile;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (InputStream in = PluginServices.getResourceAsStream("logbook/proxy.pac")) {
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
        }
        packFile = new String(out.toByteArray())
                .replace("{port}", String.valueOf(AppConfig.get().getListenPort()));

        FileChooser fc = new FileChooser();
        fc.setTitle("名前をつけて保存");
        fc.setInitialFileName("proxy.pac");

        File file = fc.showSaveDialog(this.getWindow());
        if (file != null) {

            Files.write(file.toPath(), packFile.getBytes());

            this.addr.setText("file:///" + file.toURI().toString().replaceFirst("file:/", ""));

            Tools.Conrtols.alert(AlertType.INFORMATION,
                    "自動プロキシ構成スクリプトファイル",
                    "自動プロキシ構成スクリプトファイルを生成しました。\n" + "次にブラウザの設定を行って下さい。",
                    this.getWindow());
        }
    } catch (IOException e) {
        Tools.Conrtols.alert(AlertType.ERROR,
                "自動プロキシ構成スクリプトファイル",
                "自動プロキシ構成スクリプトファイルの生成に失敗しました",
                e,
                this.getWindow());
    }
}
 
Example 12
Source File: OutputPanel.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void onOutputSheetPDFDefaultButton(final ActionEvent actionEvent)
{
	FileChooser fileChooser = new FileChooser();
	fileChooser.setTitle(LanguageBundle.getString("in_Prefs_outputSheetPDFDefaultTitle"));
	fileChooser.setInitialDirectory(new File(SettingsHandler.getPDFOutputSheetPath()));
	fileChooser.setInitialFileName(SettingsHandler.getSelectedCharacterPDFOutputSheet(null));
	File newTemplate = GuiUtility.runOnJavaFXThreadNow(() -> fileChooser.showOpenDialog(null));

	if (newTemplate != null)
	{
		if (!newTemplate.getName().startsWith("csheet") && !newTemplate.getName().startsWith("psheet"))
		{
			ShowMessageDelegate.showMessageDialog(
					LanguageBundle.getString("in_Prefs_outputSheetDefaultError"), //$NON-NLS-1$
					Constants.APPLICATION_NAME, MessageType.ERROR
			);
		}
		else
		{
			if (newTemplate.getName().startsWith("csheet"))
			{
				SettingsHandler.setSelectedCharacterPDFOutputSheet(newTemplate.getAbsolutePath(), null);
			}
			else
			{
				//it must be a psheet
				SettingsHandler.setSelectedPartyPDFOutputSheet(newTemplate.getAbsolutePath());
			}
		}
	}

	outputSheetPDFDefault.setText(String.valueOf(SettingsHandler.getSelectedCharacterPDFOutputSheet(null)));
}
 
Example 13
Source File: OutputPanel.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void onOutputSheetHTMLDefaultButton(final ActionEvent actionEvent)
{
	FileChooser fileChooser = new FileChooser();
	fileChooser.setTitle(LanguageBundle.getString("in_Prefs_outputSheetHTMLDefaultTitle"));
	fileChooser.setInitialDirectory(new File(SettingsHandler.getHTMLOutputSheetPath()));
	fileChooser.setInitialFileName(SettingsHandler.getSelectedCharacterHTMLOutputSheet(null));
	File newTemplate = GuiUtility.runOnJavaFXThreadNow(() -> fileChooser.showOpenDialog(null));

	if (newTemplate != null)
	{
		if ((!newTemplate.getName().startsWith("csheet") && !newTemplate.getName().startsWith("psheet")))
		{
			ShowMessageDelegate.showMessageDialog(
					LanguageBundle.getString("in_Prefs_outputSheetDefaultError"), //$NON-NLS-1$
					Constants.APPLICATION_NAME, MessageType.ERROR
			);
		}
		else
		{
			if (newTemplate.getName().startsWith("csheet"))
			{
				SettingsHandler.setSelectedCharacterHTMLOutputSheet(newTemplate.getAbsolutePath(), null);
			}
			else
			{
				//it must be a psheet
				SettingsHandler.setSelectedPartyHTMLOutputSheet(newTemplate.getAbsolutePath());
			}
		}
	}

	outputSheetHTMLDefault
			.setText(String.valueOf(SettingsHandler.getSelectedCharacterHTMLOutputSheet(null)));
}
 
Example 14
Source File: MainController.java    From cute-proxy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@FXML
private void exportCrt(ActionEvent e) throws CertificateEncodingException, IOException {
    var generator = Context.getInstance().sslContextManager().getKeyStoreGenerator();
    byte[] data = generator.exportRootCert(false);
    FileChooser fileChooser = new FileChooser();
    fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Crt file", "*.crt"));
    fileChooser.setInitialFileName("CuteProxy.crt");
    File file = fileChooser.showSaveDialog(this.root.getScene().getWindow());
    if (file == null) {
        return;
    }
    Files.write(file.toPath(), data);
}
 
Example 15
Source File: MainController.java    From cute-proxy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@FXML
private void exportPem(ActionEvent e) throws CertificateEncodingException, IOException {
    var generator = Context.getInstance().sslContextManager().getKeyStoreGenerator();
    byte[] data = generator.exportRootCert(true);
    FileChooser fileChooser = new FileChooser();
    fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Pem file", "*.pem"));
    fileChooser.setInitialFileName("CuteProxy.pem");
    File file = fileChooser.showSaveDialog(this.root.getScene().getWindow());
    if (file == null) {
        return;
    }
    Files.write(file.toPath(), data);
}
 
Example 16
Source File: RichTextDemo.java    From RichTextFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void saveDocument() {
    String initialDir = System.getProperty("user.dir");
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Save document");
    fileChooser.setInitialDirectory(new File(initialDir));
    fileChooser.setInitialFileName("example rtfx file" + RTFX_FILE_EXTENSION);
    File selectedFile = fileChooser.showSaveDialog(mainStage);
    if (selectedFile != null) {
        save(selectedFile);
    }
}
 
Example 17
Source File: Screenshot.java    From chart-fx with Apache License 2.0 5 votes vote down vote up
/**
 * @return The file to save the screenshot to (or null if canceled)
 */
private File showFileDialog(final String initName) {
    FileChooser fileChooser = new FileChooser();
    fileChooser.getExtensionFilters().setAll(new ExtensionFilter("PNG-Image", "*.png"));
    fileChooser.setInitialDirectory(new File(directory.get()));
    fileChooser.setInitialFileName(initName);
    File file = fileChooser.showSaveDialog(getChart().getScene().getWindow());
    if (file != null && !directory.isBound()) {
        directory.set(file.getParent());
    }
    return file;
}
 
Example 18
Source File: KovatsIndexExtractionDialog.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
private synchronized void saveToFile() {
  // need to parse
  if (!parseValues()) {
    logger.log(Level.WARNING,
        "Parsing of Kovats values failed (text box). Maybe you have to select more markers: "
            + MIN_MARKERS + " (at least)");
    return;
  }
  final TreeMap<KovatsIndex, Double> values = parsedValues;

  File lastFile =
      parameterSet.getParameter(KovatsIndexExtractionParameters.lastSavedFile).getValue();

  FileChooser chooser = new FileChooser();
  chooser.getExtensionFilters().add(csvFilter);
  if (lastFile != null)
    chooser.setInitialFileName(lastFile.getAbsolutePath());

  File f = chooser.showSaveDialog(this.getScene().getWindow());

  if (f == null)
    return;

  // set last file
  setLastFile(f);
  f = FileAndPathUtil.getRealFilePath(f, "csv");
  try {
    // save to file in GNPS GC format
    String exp = getCsvTable(values);
    if (TxtWriter.write(exp, f, false))
      saveFileListener.accept(f);
  } catch (Exception e) {
    logger.log(Level.WARNING, "Error while saving Kovats file to " + f.getAbsolutePath(), e);
  }

}
 
Example 19
Source File: LocalServerServicesController.java    From arcgis-runtime-samples-java with Apache License 2.0 4 votes vote down vote up
@FXML
private void initialize() {

  if (LocalServer.INSTANCE.checkInstallValid()) {
    LocalServer server = LocalServer.INSTANCE;

    // configure app data path (path length must be short for some services)
    appDataPath = Path.of(System.getProperty("user.home"), "EsriSamples");
    if (!appDataPath.toFile().exists()) {
      try {
        Files.createDirectory(appDataPath);
      } catch (IOException ex) {
        new Alert(AlertType.ERROR, "Failed to set local server app data path. Some processes may not work.").show();
      }
    }
    LocalServer.INSTANCE.setAppDataPath(appDataPath.toFile().getAbsolutePath());

    // log the server status
    server.addStatusChangedListener(status -> statusLog.appendText("Server Status: " + status.getNewStatus()
        .toString() + "\n"));
    // start the local server
    server.startAsync();
  } else {
    Platform.runLater(() -> {
      Alert dialog = new Alert(AlertType.INFORMATION);
      dialog.initOwner(stopServiceButton.getScene().getWindow());
      dialog.setHeaderText("Local Server Load Error");
      dialog.setContentText("Local Server install path couldn't be located.");
      dialog.showAndWait();

      Platform.exit();
    });
  }
  // create a file chooser to select package files
  packageChooser = new FileChooser();
  packagePath.textProperty().bind(packageChooser.initialFileNameProperty());
  packageChooser.setInitialDirectory(new File(System.getProperty("data.dir"), "./samples-data/local_server"));
  packageChooser.setInitialFileName(packageChooser.getInitialDirectory().getAbsolutePath() + "/PointsOfInterest.mpk");

  // create filters to choose files for specific services
  ExtensionFilter mpkFilter = new ExtensionFilter("Map Packages (*.mpk, *.mpkx)", "*.mpk", "*.mpkx");
  ExtensionFilter gpkFilter = new ExtensionFilter("Geoprocessing Packages (*.gpk, *.gpkx)", "*.gpk", "*.gpkx");
  packageChooser.getExtensionFilters().add(mpkFilter);

  // use the ComboBox to select a filter
  serviceOptions.getSelectionModel().selectedItemProperty().addListener(o -> {
    packageChooser.setInitialFileName(null);
    packageChooser.getExtensionFilters().clear();
    if ("Geoprocessing Service".equals(serviceOptions.getSelectionModel().getSelectedItem())) {
      packageChooser.getExtensionFilters().add(gpkFilter);
    } else {
      packageChooser.getExtensionFilters().add(mpkFilter);
    }
  });

  // create list view representation of running services
  runningServices.setCellFactory(list -> new ListCell<>() {

    @Override
    protected void updateItem(LocalService service, boolean bln) {

      super.updateItem(service, bln);
      if (service != null) {
        setText(service.getName() + "  :  " + service.getUrl());
      } else {
        setText(null);
      }
    }

  });

  // setup UI bindings
  stopServiceButton.disableProperty().bind(runningServices.getSelectionModel().selectedItemProperty().isNull());
  startServiceButton.disableProperty().bind(packageChooser.initialFileNameProperty().isNull());
}
 
Example 20
Source File: PCGenFrame.java    From pcgen with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * This brings up a file chooser allows the user to select
 * the location that a character should be saved to.
 * @param character the character to be saved
 */
boolean showSaveCharacterChooser(CharacterFacade character)
{
	PCGenSettings context = PCGenSettings.getInstance();
	String parentPath = lastCharacterPath;
	if (parentPath == null)
	{
		parentPath = context.getProperty(PCGenSettings.PCG_SAVE_PATH);
	}

	FileChooser fileChooser = new FileChooser();
	fileChooser.setTitle("Save PCGen Character File");
	FileChooser.ExtensionFilter extensionFilter = new FileChooser.ExtensionFilter(
			"character files only", '*' + Constants.EXTENSION_CHARACTER_FILE
	);
	fileChooser.getExtensionFilters().add(extensionFilter);
	fileChooser.setSelectedExtensionFilter(extensionFilter);

	File prevFile = character.getFileRef().get();
	if (prevFile == null || StringUtils.isEmpty(prevFile.getName()))
	{
		fileChooser.setInitialDirectory(new File(parentPath));
		fileChooser.setInitialFileName(character.getNameRef().get() + Constants.EXTENSION_CHARACTER_FILE);
	}

	File file = GuiUtility.runOnJavaFXThreadNow(() ->
			fileChooser.showSaveDialog(null));

	if (file != null)
	{
		UIDelegate delegate = character.getUIDelegate();
		if (file.isDirectory())
		{
			delegate.showErrorMessage(Constants.APPLICATION_NAME,
				LanguageBundle.getString("in_savePcDirOverwrite")); //$NON-NLS-1$
			return showSaveCharacterChooser(character);
		}

		if (file.exists() && (prevFile == null || !file.getName().equals(prevFile.getName())))
		{
			boolean overwrite = delegate.showWarningConfirm(
				LanguageBundle.getFormattedString("in_savePcConfirmOverTitle", //$NON-NLS-1$
					file.getName()),
				LanguageBundle.getFormattedString("in_savePcConfirmOverMsg", //$NON-NLS-1$
					file.getName()));

			if (!overwrite)
			{
				return showSaveCharacterChooser(character);
			}
		}

		try
		{
			character.setFile(file);
			prepareForSave(character, false);
			if (!reallySaveCharacter(character))
			{
				return showSaveCharacterChooser(character);
			}

			lastCharacterPath = file.getParent();
			return true;
		}
		catch (Exception e)
		{
			Logging.errorPrint("Error saving character to new file " + file, e); //$NON-NLS-1$
			delegate.showErrorMessage(Constants.APPLICATION_NAME,
				LanguageBundle.getFormattedString("in_saveFailMsg", file.getName())); //$NON-NLS-1$
		}
	}
	return false;
}