javafx: How do I call a method in the same class with a button action event? I have an error: "unreported exception Exception must be caught or declared to be thrown".
I am trying to create a save button to save information on a form. I know how to put the button on the GridPane.
I have a method, provided by the professor, to save form information to a file.
I do not know how to fix my code to get the button to call the method.
I've basically tried multiple permutations of moving pieces of code around in any way that might make some sense. I've searched and found what seem to be solutions for this question in other languages, but not in java, let alone using javaFX.
package programmingassignment1;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.io.*; //input/output
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
public class Address_ex extends Application {
String contactLast;
@Override
public void start(Stage primaryStage) {
TextField tf_contactLast = new TextField();
contactLast = tf_contactLast.getText();
Button bt_save = new Button("Save");
GridPane rootPane = new GridPane();
rootPane.add(new Label("Last Name"), 2, 1);
rootPane.add(tf_contactLast, 2, 2);
rootPane.add(bt_save, 5, 2);
//Setting an action for the Save button
File file = new File("AddressBook.txt");
bt_save.setOnAction(e -> {saveContact(file);});
//-> unreported exception, fileNotFoundException; must be caught or
//declared to be thrown
Scene scene = new Scene(rootPane, 1000, 500);
primaryStage.setTitle("Address Book");
primaryStage.setScene(scene);
primaryStage.show();
}
public void saveContact(File file) throws FileNotFoundException{
//->illegal start of expression
try{
PrintWriter output = new PrintWriter (file);
output.println(contactLast);
output.close();
}
catch(FileNotFoundException e){
throw new FileNotFoundException(e.getMessage());
//unreported exception Exception must be caught or declared to be thrown
}
}
public static void main(String[] args) {
launch(args);
}
}
Desired: User enters last name & clicks save then a text file is created and the last name is printed in the file.