I want to create a simple stand-alone application that will take some input from user (some numbers and mathematical functions f(x,y...)) and write them to a file. Then with
This is the way I would write to a file. I will let you convert this code into your GUI for practice. See more on BufferedWriter and FileWriter
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;
public class Files {
public static void main(String args[]){
System.out.print("Enter Text: ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter("text.txt");
writer = new BufferedWriter(fWriter);
writer.write(text);
writer.newLine();
writer.close();
System.err.println("Your input of " + text.length() + " characters was saved.");
} catch (Exception e) {
System.out.println("Error!");
}
}
}
For your second question, you may like to consider having a JTextField on your JFrame for the user to enter lines into instead of a JOptionPane. It's just a simple text box, and you can add the box's contents to the file every time the button is pressed:
public static void main(String[] args) {
JTextField myTextField = new JTextField();
// Your code, set size and position of textfield
panel.add(myTextField);
}
class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String text = myTextField.getText();
myTextField.setText("");
new BufferedWriter(new FileWriter("text.txt")).write(text).newLine().close();
// the rest of your code
}
}