我试图通过按下JavaFx中的按钮将数据写入文本文件。但是唯一的问题是,当我尝试使用声明,“在我的按钮处理方法中抛出IOException”时,事情似乎不起作用。这是我的代码。如何捕捉javafx中的IOException
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.control.Button;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
public class testingFx extends Application{
//Create controls
private Button write;
private Scene main;
private Button Exit;
private Scene sceneMain;
private File records;
private FileWriter fw;
public static void main(String[] args){
launch(args);
}
@Override
public void start(Stage stage) throws IOException{
//Create new file
records = new File("records.txt");
records.createNewFile();
//Create FileWriter
fw = new FileWriter(records);
//Create root, format controls, scene, etc...
Group root = new Group();
write = new Button();
write.setText("Write");
write.setOnAction(this::processButtonPress);
root.getChildren().addAll(write);
main = new Scene(root,300,300);
stage.setScene(main);
stage.show();
}
public void processButtonPress(ActionEvent event) throws IOException{
if (event.getSource() == write){
//On button press write to file
fw.write("Testing file writing");
//Close filewriter
fw.close();
}
}
}
我试图在网上找到答案,但我被教导要处理按下按钮的方式,从大多数人的例子(也称部分(这:: processButtonPress))不同。我不确定是否使用try/catch语句可以帮助我,因为我没有任何经验,请原谅我。我特别要得到的错误是“错误:方法参考中出现不兼容的抛出类型IOException”。感谢您的帮助。
我试着在主题上提出这个问题,并且很容易解决。请让我知道是否有任何明显的问题。
你必须处理方法中IOException异常。 – f1sh