Hi!
I'm trying to make a program with gui. The window should have 2 textfields and one button. One of the textfield are uneditable. When the button is clicked i want the stuff from the first textfield to be written to a file and I want the second textfield to output the text from the file. The gui works fine, but whenever I press the button i get a bunch of errors. This is the code I'm using:
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class GUI extends JFrame{ private JTextField toFile; private JTextField fromFile; private JButton sendToFile; private FileHandling fh; public GUI(){ super("File"); setLayout(new FlowLayout()); toFile = new JTextField("Write what you want to send to the file",20); add(toFile); sendToFile=new JButton("Add to file"); add (sendToFile); fh=new FileHandling(); fh.checkFile(); fh.readFile(); fromFile=new JTextField(fh.fromFile,20); fromFile.setEditable(false); add(fromFile); HandlerClass hc=new HandlerClass(); sendToFile.addActionListener(hc); } private class HandlerClass implements ActionListener{ public void actionPerformed(ActionEvent event){ String a=fromFile.getText(); fh.writeFile(a); } } }
import java.io.*; import java.util.*; public class FileHandling { private Formatter x; private Scanner s; private File y; public String fromFile; public void checkFile(){ y=new File("data.txt"); if(y.exists()){ try{ s=new Scanner(y); } catch(Exception e){ System.out.println("Could not scan the file"); } }else{ try{ x=new Formatter("data.txt"); s=new Scanner(y); } catch(Exception e){ System.out.println("Could not create the file"); } } } public void readFile(){ while(s.hasNextLine()){ fromFile=s.nextLine(); } } public void writeFile(String a){ x.format("%s \n", a); } public void closeFile(){ x.close(); } }
If anyone can tell me what I'm doing wrong I would be very grateful.