我已经使用javafx创建了小型Java程序。在我试图保存任何文本文件或Java文件。 将文件保存在预期的位置但没有扩展名,这可能是一个愚蠢的问题,但是我对javaFX没有任何经验,
1.Main.java
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
2.Controller.java
package sample;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.stage.FileChooser;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Controller {
@FXML
private TextArea TextArea;
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
void OnButtonClicked(ActionEvent event) {
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Java files (*.java)", "*.java");
fileChooser.getExtensionFilters().add(extFilter);
File selectedFile = fileChooser.showSaveDialog(null);
if(selectedFile != null){
SaveFile(TextArea.getText(), selectedFile);
}
}
private void SaveFile(String content, File file){
try {
FileWriter fileWriter;
fileWriter = new FileWriter(file);
fileWriter.write(content);
fileWriter.close();
} catch (IOException ex) {
Logger.getLogger(Main.class
.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
void initialize() {
}
}
3.sample.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<children>
<Button layoutX="269.0" layoutY="275.0" mnemonicParsing="false" onAction="#OnButtonClicked" text="Save" />
<TextArea fx:id="TextArea" layoutX="169.0" layoutY="14.0" prefHeight="200.0" prefWidth="200.0" />
</children>
</AnchorPane>
我目前是JavaFx和Java技术的新手,将不胜感激!!!
答案 0 :(得分:0)
FileChooser中的过滤器仅用于过滤活动文件夹中的现有文件。如果要添加默认文件扩展名,则需要类似以下内容的文件:
String fileName = file.toString();
if (!fileName.endsWith(".java"))
fileName += ".java";