以下是一个简单的示例代码,演示了如何在JavaFX中保存输入的数据。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class SaveInputData extends Application {
@Override
public void start(Stage primaryStage) {
TextField textField = new TextField();
Button saveButton = new Button("Save");
saveButton.setOnAction(event -> {
String inputData = textField.getText();
saveDataToFile(inputData);
});
VBox vbox = new VBox(textField, saveButton);
Scene scene = new Scene(vbox, 300, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
private void saveDataToFile(String data) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("data.txt"))) {
writer.write(data);
System.out.println("Data saved to file.");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
在上述示例中,我们创建了一个JavaFX应用程序,其中包含一个文本框和一个保存按钮。当用户点击保存按钮时,我们将获取文本框中的输入数据,并将其保存到名为"data.txt"的文件中。
请注意,我们使用了BufferedWriter
和FileWriter
来将数据写入文件中。在实际开发中,可能需要根据需要进行错误处理和文件路径的设置。