Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Saving text into a file from GUI input

843806Aug 13 2007 — edited Aug 14 2007
Hi,

I'm having some trouble trying to create a code where I can save my data from a user input.
-This is how the program works:
-a user inputs a value into the textfield, then the user hits the save button where the data will be saved into a textfile.
-so far it doesn't write to file

Here's my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

public class Rental extends JFrame
{
	JTextField textOne;
	JButton button;
	
	public Rental()
	{
		build();
		setSize(400, 140);
		setVisible(true);
		setLocationRelativeTo(null); //center the window
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public static void main(String[] args)
	{
		new Rental();
	}
	
	public void build()
	{
		textOne = new JTextField(7);
		button = new JButton("Click");
		button.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				save();
			}});
		
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new BorderLayout(4, 4));
		add(mainPanel, BorderLayout.NORTH);
		
		JPanel fieldPanel = new JPanel();
		mainPanel.add(fieldPanel, BorderLayout.CENTER);
		
		JPanel fieldPanel2 = new JPanel();
		mainPanel.add(fieldPanel2, BorderLayout.EAST);
		
		fieldPanel2.add(textOne);
		fieldPanel.add(button);
	}
	
	public void save()
	{
		String combine;
		Scanner scan; 
		PrintWriter output;
		File file = new File("RentalAgreements.txt");
		
		String text = textOne.getText();
		try{
		output = new PrintWriter("RentalAgreements.txt");
		scan = new Scanner(new BufferedReader(new FileReader("RentalAgreements.txt")));
	    while (scan.hasNext())
        {
        	if(!scan.hasNext())
        		scan.next();
	        combine = scan.next(text);
	        output.print(combine);
        }
        if (scan != null) 
        	scan.close();
        output.close();
		}catch(FileNotFoundException e){
			System.out.println(e);
		}
	}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 11 2007
Added on Aug 13 2007
9 comments
1,733 views