Submit button data written to a .txt file

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 14765 Views - Last Post: 08 April 2012 - 10:56 AM Rate Topic: -----

#1 Ziul  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 18-July 07

Submit button data written to a .txt file

Post icon  Posted 08 August 2007 - 01:50 PM

I have created an application using Swing that takes data that an user enters into textfields and once they press the submit button, the entered data is written to an external text file (program.txt), which I have placed in the same directory as the application.

Attached Image
Attached Image

I can then open my application and click 'Display Data' under my Functions menu selection and view the results in that window through a TextArea with a scrollpane, pulling the data from the text file (program.txt) that the data submitted was written to.

Attached Image

I am having trouble and have tried various approaches with my code and any help here would be appreciated by someone more knowledgeable.

Here is my code:

import java.awt.*; //declare packages needed
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.JMenuBar;


public class FinalProgram extends JFrame 
	implements ActionListener {

static JFrame frame; 

  public void actionPerformed (ActionEvent e) { 

	  String answer = (e.getActionCommand());
	  
		if (answer == "Get Data") {
		
		JInternalFrame iFrame = new JInternalFrame("Get Data . ", false, true, false, false);
		iFrame.setLayout(new GridLayout(8,2));
		
		
		
		JLabel label1 = new JLabel("First Name");
		JLabel label2 = new JLabel("Last Name");
		JLabel label3 = new JLabel("Street");
		JLabel label4 = new JLabel("City");
		JLabel label5 = new JLabel("State");
		JLabel label6 = new JLabel("Zip");
		JLabel label7 = new JLabel("Phone");
		JLabel label8 = new JLabel("Click Button to Submit Form -->");
		
		
		JTextField textfield1 = new JTextField(10);
		JTextField textfield2 = new JTextField(10);
		JTextField textfield3 = new JTextField(10);
		JTextField textfield4 = new JTextField(10);
		JTextField textfield5 = new JTextField(10);
		JTextField textfield6 = new JTextField(10);
		JTextField textfield7 = new JTextField(10);
		JButton button1 = new JButton("Submit Data"); [COLOR="Red"]//here is button1[/COLOR]
		
		
		textfield1.addActionListener(this);
		textfield2.addActionListener(this);
		textfield3.addActionListener(this);
		textfield4.addActionListener(this);
		textfield5.addActionListener(this);
		textfield6.addActionListener(this);
		textfield7.addActionListener(this);
		button1.addActionListener(this);
		
		//textfield1.setSize(10, 10);
		
		iFrame.add(label1);
		iFrame.add(textfield1);
		iFrame.add(label2);
		iFrame.add(textfield2);
		iFrame.add(label3);
		iFrame.add(textfield3);
		iFrame.add(label4);
		iFrame.add(textfield4);
		iFrame.add(label5);
		iFrame.add(textfield5);
		iFrame.add(label6);
		iFrame.add(textfield6);
		iFrame.add(label7);
		iFrame.add(textfield7);
		iFrame.add(label8);
		iFrame.add(button1);
		
	try { [COLOR="Red"]//problem starts here[/COLOR]
	  String directoryName = "c:\\javacode\\Notepad"; [COLOR="Red"]//I've created my variable to hold my directory where my .txt file is to be pulled from[/COLOR]
	  String fileName = "program.txt"; [COLOR="Red"]//variable that holds my text file name[/COLOR]
	  File output = new File(directoryName,fileName); [COLOR="Red"]//File object that points to the directory and file[/COLOR]
	  output.createNewFile(); [COLOR="Red"]//if file is not created, create it[/COLOR]
	  
	  if (! output.isFile()) { [COLOR="Red"]//if it can't be created, output an error message[/COLOR]
	System.out.println("File creation of" + output.getPath() 
				+ "failed");
		return;
	  }
	  
	  //put an if statement here
	  
	  if (e.getSource() == button1) { [COLOR="Red"]//I feel I'm doing something wrong here, I'm trying to get the when the button (button1 created above) is pushed, to then execute the code below.[/COLOR]
	BufferedWriter out = new BufferedWriter(new FileWriter(output.getPath(), true));
				  
				[COLOR="Red"]//This part here is all test code below, that when the button (button1) is pressed, this code is executed and this text is written to a data file, once I confirm a button press I can move on to taking the data input into each of the separate textFields from the form and writing it, one step at a time, I'm beginner.[/COLOR]
	String[] text = {"This is the text that will be written. \r", //we pass an array, which holds the text to append to the file
			 "The text will be written to the file \r",
			 "in append mode. If the file does not \r",
			 "exist it will be created.\r"};
	for(int i = 0; i < text.length; i++) {
	  out.write(text[i] + "\n");
	}
	
	out.close();
	}
	 }
	 catch(IOException d) {
	System.out.println("Error writing to file " + d);
	 }
	 [COLOR="Red"]//all other code outside of these red words works fine as you can see in the pictures, I'll accept any suggestions as I'll be working on this still.[/COLOR]
	 
   
		
		iFrame.setSize(200, 500);
		iFrame.setVisible(true);
		
		add(iFrame);
		
	  }
	  
		if (answer == "Display Data") {
		
		JInternalFrame iFrame = new JInternalFrame("Display Data . ", false, true, false, false);
		
		JTextArea text = new JTextArea();
		JScrollPane scroller = new JScrollPane();
		scroller.getViewport().add(text);
		
		iFrame.getContentPane().add(scroller);
		iFrame.setSize(200, 150);
		iFrame.setVisible(true);
		add(iFrame);
		}

  }

  public FinalProgram() { 
	super ("Menu Example");
   

	JMenuBar jmb = new JMenuBar(); 
	JMenu file = new JMenu("Functions"); 
	JMenuItem item;
	file.add(item = new JMenuItem("Get Data"));
	item.addActionListener (this);
	file.add(item = new JMenuItem("Display Data"));
	item.addActionListener (this);

	jmb.add(file);
	

	
	addWindowListener(new ExitListener());	 
	setJMenuBar (jmb);
  }


	public static void main(String[] args) { 
	
		FinalProgram window = new FinalProgram();
		window.setTitle("Final Program");
		window.setSize(600, 600);
		window.setVisible(true);
		
	}
}


Is This A Good Question/Topic? 0
  • +

Replies To: Submit button data written to a .txt file

#2 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 251
  • View blog
  • Posts: 1,833
  • Joined: 02-January 06

Re: Submit button data written to a .txt file

Posted 08 August 2007 - 01:53 PM

What problems are you having? If you're getting exceptions, paste the exact stack trace here so we can help you. If it's not an exception, describe your problem.
Was This Post Helpful? 0
  • +
  • -

#3 Ziul  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 18-July 07

Re: Submit button data written to a .txt file

Posted 08 August 2007 - 02:00 PM

View Postalcdotcom, on 8 Aug, 2007 - 01:53 PM, said:

What problems are you having? If you're getting exceptions, paste the exact stack trace here so we can help you. If it's not an exception, describe your problem.


Thanks for your reply. No exceptions as the code is right now. The primary problem is, my code does not write anything to the text file once the 'Submit Data' button is pressed, the code within the if statement for e.getSource doesn't write the text to the text file once I press the button in my application, does this make sense?
Was This Post Helpful? 0
  • +
  • -

#4 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 251
  • View blog
  • Posts: 1,833
  • Joined: 02-January 06

Re: Submit button data written to a .txt file

Posted 08 August 2007 - 03:25 PM

Please upload all of your source code. The code snippet you posted is muddled with bbcode. BTW - you can't use bbcode within code tags because it won't interpret them.
Was This Post Helpful? 0
  • +
  • -

#5 Ziul  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 18-July 07

Re: Submit button data written to a .txt file

Posted 08 August 2007 - 04:09 PM

Here is my source Code, I have cleaned it up and deleted the stuff that might not make sense to communicate this problem more effectively.

I've developed a format below to make this clearer, thanks again for your help.

Gray = code that works fine
Black = area of problem code
Red = comments for debugging purposes

import java.awt.*; //declare packages needed
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.JMenuBar;


public class FinalProgram extends JFrame
implements ActionListener {

static JFrame frame;

public void actionPerformed (ActionEvent e) {

String answer = (e.getActionCommand());

if (answer == "Get Data") {

JInternalFrame iFrame = new JInternalFrame("Get Data . ", false, true, false, false);
iFrame.setLayout(new GridLayout(8,2));



JLabel label1 = new JLabel("First Name");
JLabel label2 = new JLabel("Last Name");
JLabel label3 = new JLabel("Street");
JLabel label4 = new JLabel("City");
JLabel label5 = new JLabel("State");
JLabel label6 = new JLabel("Zip");
JLabel label7 = new JLabel("Phone");
JLabel label8 = new JLabel("Click Button to Submit Form -->");


JTextField textfield1 = new JTextField(10);
JTextField textfield2 = new JTextField(10);
JTextField textfield3 = new JTextField(10);
JTextField textfield4 = new JTextField(10);
JTextField textfield5 = new JTextField(10);
JTextField textfield6 = new JTextField(10);
JTextField textfield7 = new JTextField(10);
JButton button1 = new JButton("Submit Data"); //here is the 'Submit Data' button


textfield1.addActionListener(this); //add actionlisteners to each textfield to later grab the info
textfield2.addActionListener(this);
textfield3.addActionListener(this);
textfield4.addActionListener(this);
textfield5.addActionListener(this);
textfield6.addActionListener(this);
textfield7.addActionListener(this);
button1.addActionListener(this); //add an actionlistener to our 'Submit Data' button, maybe I'm missing a getSource() here?

//textfield1.setSize(10, 10);

iFrame.add(label1);
iFrame.add(textfield1);
iFrame.add(label2);
iFrame.add(textfield2);
iFrame.add(label3);
iFrame.add(textfield3);
iFrame.add(label4);
iFrame.add(textfield4);
iFrame.add(label5);
iFrame.add(textfield5);
iFrame.add(label6);
iFrame.add(textfield6);
iFrame.add(label7);
iFrame.add(textfield7);
iFrame.add(label8);
iFrame.add(button1);


try {
String directoryName = "c:\\javacode\\Notepad"; //variable holding directory information
String fileName = "program.txt"; //variable holding text file name information, this text file is completely empty, waiting for the textField information
File output = new File(directoryName,fileName); //File object containing our directory and file information
output.createNewFile(); //create the file if there isn't one already

if (! output.isFile()) { //generate error message if one cannot be created
System.out.println("File creation of" + output.getPath()
+ "failed");
return;
}

//put an if statement here, so that IF the 'Submit Data' button has been pressed, take the data from the textFields and write them to file (run the code within the brackets)


BufferedWriter out = new BufferedWriter(new FileWriter(output.getPath(), true));

//Here I create the code to grab the actions(grab the text) from the textFields and store them into variables OR into an array

//after I have created my container to hold the information for my various textFields, then I want to create a for loop to go through each textField and write that information to a text file, separating each textField on its own line
out.close();
}

catch(IOException d) {
System.out.println("Error writing to file " + d);
}




iFrame.setSize(200, 500);
iFrame.setVisible(true);

add(iFrame);

}

if (answer == "Display Data") {

JInternalFrame iFrame = new JInternalFrame("Display Data . ", false, true, false, false);

JTextArea text = new JTextArea();
JScrollPane scroller = new JScrollPane();
scroller.getViewport().add(text);

iFrame.getContentPane().add(scroller);
iFrame.setSize(200, 150);
iFrame.setVisible(true);
add(iFrame);
}

}

public FinalProgram() {
super ("Menu Example");


JMenuBar jmb = new JMenuBar();
JMenu file = new JMenu("Functions");
JMenuItem item;
file.add(item = new JMenuItem("Get Data"));
item.addActionListener (this);
file.add(item = new JMenuItem("Display Data"));
item.addActionListener (this);

jmb.add(file);



addWindowListener(new ExitListener());
setJMenuBar (jmb);
}


public static void main(String[] args) {

FinalProgram window = new FinalProgram();
window.setTitle("Final Program");
window.setSize(600, 600);
window.setVisible(true);

}
}

Was This Post Helpful? 0
  • +
  • -

#6 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 251
  • View blog
  • Posts: 1,833
  • Joined: 02-January 06

Re: Submit button data written to a .txt file

Posted 08 August 2007 - 04:41 PM

That's not what I meant by "upload", but I'll let it slide. ;)

When I run your app, the file is never created. I recommend that you stick to the File ( String fileName ) constructor and just save the file in the main project directory for testing purposes. The other thing I see is that you are not actually writing anything to the file when the button is pressed. Create the logic to detect a button press and then I recommend using a StringBuffer to store all of the data from the forms. Then you can write it all to the file on one chunk.

On a side note, it is often easier (especially for small projects/prototypes like this) to give each component it's own listener using anonymous inner classes:

button1.addActionListener(new ActionListener()
{
	public void actionPerformed(ActionEvent e) {
		// do stuff
	}
});


If you do this for each of your components you won't have to use if statements.
Was This Post Helpful? 0
  • +
  • -

#7 Ziul  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 18-July 07

Re: Submit button data written to a .txt file

Posted 08 August 2007 - 08:15 PM

A button press is detected using actionListener. I have tried your advice and modified the code to suit the applications purposes.

I am unfamiliar with a StringBuffer, I haven't learned that method yet, so what I'm trying to do is this:


JTextField textfield1 = new JTextField(10);
JTextField textfield2 = new JTextField(10);
JTextField textfield3 = new JTextField(10);
JTextField textfield4 = new JTextField(10);
JTextField textfield5 = new JTextField(10);
JTextField textfield6 = new JTextField(10);
JTextField textfield7 = new JTextField(10);
JButton button1 = new JButton("Submit Data");


textfield1.addActionListener(this);
textfield2.addActionListener(this);
textfield3.addActionListener(this);
textfield4.addActionListener(this);
textfield5.addActionListener(this);
textfield6.addActionListener(this);
textfield7.addActionListener(this);

button1.addActionListener(new ActionListener() { //start button1.addActionListener
public void actionPerformed(ActionEvent a) { //start button1 actionPerformed
String pressed = ((JButton) a.getSource()).getText();
System.out.println("It is detected " + pressed); //here I am running a test to check that when the button press is detected to System.out.println a message, this works


try {
String directoryName = "c:\\javacode\\Notepad";
String fileName = "program.txt";
File output = new File(directoryName,fileName);
output.createNewFile();

if (! output.isFile()) {
System.out.println("File creation of" + output.getPath() + "failed");
return;
}

BufferedWriter out = new BufferedWriter(new FileWriter(output.getPath(), true));

String[] text = {textfield1, textfield2, textfield3, textfield4, textfield5, textfield6, textfield7}; //Here I'm trying to put all my textfield data for every textfield into an element of the above array, here I am not sure it will work this way, put short, take the data from every field...

for(int i = 0; i < text.length; i++) { //and output each textfield with a for loop on its own line, I'm not sure this is the most effective way to do it, I'm experimenting right now, any thoughts?
out.write(text[i] + "\n");
}


//Here I create the code to grab the actions(grab the text) from the textFields and store them into variables OR into an array

//after I have created my container to hold the information for my various textFields, then I want to create a for loop to go through each textField and write that information to a text file, separating each textField on its own line
out.close();
}

catch(IOException d) {
System.out.println("Error writing to file " + d);
}

} //end button1.addActionListener
} //end button1 actionPerformed
); //end actionListener statement

Was This Post Helpful? 0
  • +
  • -

#8 1lacca  Icon User is offline

  • code.rascal
  • member icon

Reputation: 44
  • View blog
  • Posts: 3,822
  • Joined: 11-August 05

Re: Submit button data written to a .txt file

Posted 09 August 2007 - 12:30 AM

I'm referring to your original code here (and I hope I understand what you want to do actually).
Your original use of ActionListener was OK, the problem was that you've compared strings with the == operator if (answer == "Get Data") . This is wrong! Use the equals method to compare Strings.
Second: your feeling of missing a getSource is right. I would suggest setting the action command for that button as well (JButton.setActionCommand(String) ) and modify the actionPerformed function like this:
if(answer.equals("Get Data"){
// show the gui
...
}else if(answer.equals("Submit"){
// write things to the file
...
}



edit: some really freaky spelling, omg :o

This post has been edited by 1lacca: 09 August 2007 - 07:15 AM

Was This Post Helpful? 1
  • +
  • -

#9 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 251
  • View blog
  • Posts: 1,833
  • Joined: 02-January 06

Re: Submit button data written to a .txt file

Posted 09 August 2007 - 07:04 AM

Maybe I wasn't clear. I never said you were misusing the ActionListener. My suggestion was just another way of doing it. I like to have a function, called from tjhe constructor, that adds all of the listeners as anonymous inner classes. But, like I said - just a suggestion. 1lacca is right about comparing strings using equals. I didn't even notice because that part of the code was working for me. However, when you use anonymous inner classes for Listeners, you don't need to compare Strings. :)

This post has been edited by alcdotcom: 09 August 2007 - 07:17 AM

Was This Post Helpful? 0
  • +
  • -

#10 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 251
  • View blog
  • Posts: 1,833
  • Joined: 02-January 06

Re: Submit button data written to a .txt file

Posted 09 August 2007 - 07:14 AM

Here is the best resource for learning Java 1.6 classes on the net:
http://java.sun.com/javase/6/docs/api/

Click the white space in the bottom left window to give it focus (it won't look like it's focused, but it is) and then do a search (Ctrl-F in Firefox) for the class you want. In this case, look for StringBuffer. When you click on the StringBuffer link the API for that class will load in the frame on the right. Here is the page:
http://java.sun.com/...ringBuffer.html

You will see a list of all of the constructors and methods. The basic pattern is
1. create StringBuffer.
2. Append data (possibly multiple times)
3. use toString() method to get whole String from StringBuffer
Was This Post Helpful? 0
  • +
  • -

#11 1lacca  Icon User is offline

  • code.rascal
  • member icon

Reputation: 44
  • View blog
  • Posts: 3,822
  • Joined: 11-August 05

Re: Submit button data written to a .txt file

Posted 09 August 2007 - 07:29 AM

I prefer the way he used the ActionListener originally, because it makes code reuse easier, and doesn't generate a bunch of anonymous classes, but it's just a matter of personal taste I guess, both methods are correct, and none of them were misused, sorry for the confusion :o
Btw I am really interested alcdotcom, why do you prefer this method, what advantage does it has? I see there are many different common practices for the implementation of listeners, if I remember well William Wilson mentioned a couple of times, that all of them should be implemented in a separate class - I guess because it makes GUI modularization easier (reuse and separation), but usually some of the listeners are so tightly coupled that I think they are better to keep together (even Sun's abstract classes implement multiple listeners), and they are not even supposed to be in a separate class. As opposed to this post, which should have been done somewhere else, but I'll start another thread if it starts an interesting discussion.
Was This Post Helpful? 0
  • +
  • -

#12 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 251
  • View blog
  • Posts: 1,833
  • Joined: 02-January 06

Re: Submit button data written to a .txt file

Posted 09 August 2007 - 07:45 AM

View Post1lacca, on 9 Aug, 2007 - 07:29 AM, said:

I prefer the way he used the ActionListener originally, because it makes code reuse easier, and doesn't generate a bunch of anonymous classes, but it's just a matter of personal taste I guess, both methods are correct, and none of them were misused, sorry for the confusion :o
Btw I am really interested alcdotcom, why do you prefer this method, what advantage does it has? I see there are many different common practices for the implementation of listeners, if I remember well William Wilson mentioned a couple of times, that all of them should be implemented in a separate class - I guess because it makes GUI modularization easier (reuse and separation), but usually some of the listeners are so tightly coupled that I think they are better to keep together (even Sun's abstract classes implement multiple listeners), and they are not even supposed to be in a separate class. As opposed to this post, which should have been done somewhere else, but I'll start another thread if it starts an interesting discussion.

What I sad was, "it is often easier (especially for small projects/prototypes like this) to give each component it's own listener using anonymous inner classes." Small projects and prototypes typically are more concerned with proof-of-concept than reusability. That comes later with the "real" design and refactoring. The reason I like to use this method in these cases is because it negates the need for a bunch of if-then-else or switch logic. I call an addListeners() method or something like that, during object construction. In this method, I will add listeners using anonymous inner classes for all of my components, so all of my event handling code is in the same place. Now, if I'm doing anything larger, I use a different method. I like to use an event "multicaster" class which catches all events and routes them to the correct listener(s). When I do this I create Listeners in separate classes, or inner (not anonymous) classes.
Was This Post Helpful? 0
  • +
  • -

#13 1lacca  Icon User is offline

  • code.rascal
  • member icon

Reputation: 44
  • View blog
  • Posts: 3,822
  • Joined: 11-August 05

Re: Submit button data written to a .txt file

Posted 09 August 2007 - 08:40 AM

Sorry, I saw that you've recommended this method for smaller and prototype projects, but wanted to ask a general question about listeners, and I've guessed you have an alternative method for bigger ones.
Anyway, sounds like a useful architecture you are using.
Was This Post Helpful? 0
  • +
  • -

#14 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 251
  • View blog
  • Posts: 1,833
  • Joined: 02-January 06

Re: Submit button data written to a .txt file

Posted 09 August 2007 - 09:03 AM

View Post1lacca, on 9 Aug, 2007 - 08:40 AM, said:

Sorry, I saw that you've recommended this method for smaller and prototype projects, but wanted to ask a general question about listeners, and I've guessed you have an alternative method for bigger ones.
Anyway, sounds like a useful architecture you are using.

The event multicaster is very useful when you want to loosely couple parts of your app. I used it in my RSS reader which had several "panes" in one window that reacted to each other. When I chose a feed in one pane, another would show the list of messages in that feed. Neither of these pieces knew about the other, but they passed events via the multicaster. I may revisit this later to see if there is a better way, but currently I'm stuck in J2EE land. :)
Was This Post Helpful? 0
  • +
  • -

#15 1lacca  Icon User is offline

  • code.rascal
  • member icon

Reputation: 44
  • View blog
  • Posts: 3,822
  • Joined: 11-August 05

Re: Submit button data written to a .txt file

Posted 09 August 2007 - 09:08 AM

Same thing here, I haven't created an ActionListener in ages, everything is about HttpServletRequests :)
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2