Writing/Reading an ArrayList from a file.
This is my save... not sure if i'm writing to file correctly. it's writing my toString which looks like this... now it saves everything to a file.. but i can't read it.. I NEED DESPERATE HELP!
public String toString(){
return title +""+ author +""+ publisher +"\n";
}
publicvoid actionPerformed(ActionEvent evt){
try
{
JFileChooser chooser;
File file, directory;
int status;
chooser =new JFileChooser();
status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION)
{
file= chooser.getSelectedFile();
directory = chooser.getCurrentDirectory();
PrintWriter pW =new PrintWriter(file);
pW.print(book);
pW.close();
}
else
{
JOptionPane.showMessageDialog(null,"Save File dialog canceled");
}
}
catch (Exception ex)
{
}
}
This is my read.. it doesn't work, because i want the values from the value to be taken and put into the GUI window...
try
{
String inRecord;
String inStoreNum, inStoreName, inStoreSales;
JFileChooser chooser;
File file, directory;
int status;
chooser =new JFileChooser();
status = chooser.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION)
{
file= chooser.getSelectedFile();
directory = chooser.getCurrentDirectory();
FileReader fr =new FileReader(file);
BufferedReader br =new BufferedReader(fr);
while ((inRecord = br.readLine()) !=null)
{
StringTokenizer tokenizer =new StringTokenizer(inRecord);
titleField.setText.getTitle() = tokenizer.nextToken();;
authorField.setText.getAuthor() = tokenizer.nextToken();;
publisherField.setText.getPublisher() = tokenizer.nextToken();;
System.out.println(titleField);
}
}
else
{
JOptionPane.showMessageDialog(null,"Open File dialog canceled");
}
}
catch (Exception ex)
{
}
[3543 byte] By [
DenisKa] at [2007-11-27 10:52:35]

Serialization is your friend:
import java.util.ArrayList;
import java.util.List;
import java.io.*;
class SerialTest {
public static void main(String[] argv) throws Exception {
List<String> list = new ArrayList<String>();
list.add("Caleb");
list.add("Ned");
list.add("Sally");
list.add("Fred");
File f = new File("test.fil");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
oos.close();
System.out.println("Stored the list to a file.");
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
List<String> newList = (ArrayList<String>)ois.readObject();
ois.close();
for( String s : newList) System.out.println(s);
}
}
Serializable won't work with what i need.... each index in the array list holds 3 values... title, author, publisher.. those are written to a file along with all the entries .. than those entries must be opened and re-displayed onto the gui..
I kind of having it going now...
here's the write.. when it writes to file.. it adds brackets.. like [ 1 1 1, 2 2 2 ] and etc.. is there anyway to remove them? when i read the file it brings the brackets in aswell..
public void actionPerformed(ActionEvent evt) {
try
{
JFileChooser chooser;
File file, directory;
int status;
chooser = new JFileChooser();
status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION)
{
file= chooser.getSelectedFile();
directory = chooser.getCurrentDirectory();
PrintWriter pW = new PrintWriter(file);
pW.print(book);
pW.close();
}
else
{
JOptionPane.showMessageDialog(null, "Save File dialog canceled");
}
}
catch (Exception ex)
{
}
}
heres the read.. don't mind the variable names.. i stole it right from an example from the teacher..
private void openMenu() {
try
{
JFileChooser chooser;
File file, directory;
int status;
chooser = new JFileChooser();
status = chooser.showSaveDialog(null);
file= chooser.getSelectedFile();
directory = chooser.getCurrentDirectory();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String inRecord;
String inStoreNum, inStoreName, inStoreSales;
int storeCount = 0;
double totalSales = 0;
while ((inRecord = br.readLine()) != null)
{
StringTokenizer tokenizer = new StringTokenizer(inRecord);
inStoreNum = tokenizer.nextToken();
inStoreName = tokenizer.nextToken();
inStoreSales = tokenizer.nextToken();
System.out.println(inStoreNum + "" + inStoreName + " " + inStoreSales);
}
}
catch (Exception ex)
{
}
}
> Serializable won't work with what i need.
Yes it will.
>... each
> index in the array list holds 3 values... title,
> author, publisher..
What makes you think you can't use Serializable with this?
> those are written to a file
Or this?
> along
> with all the entries
Or this?
> .. than those entries must be
> opened and re-displayed onto the gui..
Or this?
jverda at 2007-7-29 11:38:25 >

I tried but it doesn't work?
I tried putting it into my code but everytime i print the object it doesn't print the stuff in the arraylist, but rather this hashcode or something..
Keep in mind my teacher said we don't need to use serializable for this.. he didn't even get into serializable at all..
what did your serialization deserialization routines look like? Do you mind demonstrating them? Perhaps you implemented them incorrectly, and someone can correct it here.
Well i looked at Navy's code and pretty much tried copying it, but when i printed the object it printed out some hashcode instead of the actual values.
> I tried but it doesn't work?
What exactly did you try and how exactly did it not work?
jverda at 2007-7-29 11:38:25 >

> Well i looked at Navy's code and pretty much tried
> copying it,
Did you understand it before copying and using it?
> but when i printed the object it printed
> out some hashcode instead of the actual values.
Then you're either printing the wrong thing, or you didn't override toString somewhere that you need to.
jverda at 2007-7-29 11:38:25 >

This code writes this to a file...
sr java.util.ArrayListxa I sizexpw
x
I can't even explain it anymore, nothings working.
try
{
List<String> book = new ArrayList<String>();
File f = new File("input111.txt");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(book);
oos.close();
}
catch (Exception ex)
{
}
> This code writes this to a file...
>
> sr java.util.ArrayListxa I sizexp
Serialized data is not intended to be human readable. You read it back into your program with ObjectReader.readObject.
If you want human readable, use your own format or java.beans.XMLEncoder/Decoder.
jverda at 2007-7-29 11:38:25 >

> I can't even explain it anymore, nothings working.
That part is working just fine.
jverda at 2007-7-29 11:38:25 >

So you're telling me that's right?mhm. ok, now i'll try reading.
> So you're telling me that's right?
Well, I can't personally read that format, but I have no reason to believe it's wrong.
jverda at 2007-7-29 11:38:25 >

When i try this, it doesn't print out anything..
File f = new File("input111.txt");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(book);
oos.close();
FileInputStream fis = new FileInputStream("input111.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
List<String> newList = (ArrayList<String>)ois.readObject();
ois.close();
for( String s : newList) System.out.println(s);
What would you expect it to print and why?
jverda at 2007-7-29 11:38:30 >

I was expecting it to print out the stuff in ArrayList book. Because it wrote book to the file(or so i think) and the read is converting it back and being printed onto the terminal?
I have no idea what.. this does
List<String> newList = (ArrayList<String>)ois.readObject();
> I was expecting it to print out the stuff in
> ArrayList book. Because it wrote book to the file(or
> so i think) and the read is converting it back and
> being printed onto the terminal?
Did you try printing the list immediately before writing it out to the file to verify that it had something in it?
> I have no idea what.. this does
> List<String> newList =
> st = (ArrayList<String>)ois.readObject();
What part don't you understand? If it's the readObject method, then read the docs for it.
jverda at 2007-7-29 11:38:30 >

This is almost always a bad idea: catch (Exception ex) {}
You're saying, "If anything goes wrong, don't tell me about it. Just pretend everything is fine."
You should at the very least call ex.printStackTrace(). Even that's not proper exception handling, but at least you'll see what went wrong.
jverda at 2007-7-29 11:38:30 >

[ 1 1 1 , 2 2 2 ]
java.io.NotSerializableException: BookMaintenance
thats printed when i use
File f = new File("input111.txt");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
System.out.println(book);
oos.writeObject(book);
oos.close();
Well, there you have it.
You haven't made your BookMaintenance class implement Serializable, so of course nothing got written to the file.
jverda at 2007-7-29 11:38:30 >

Ok, i made it implement Serializable, the file has something, but it's not readable, is there a way to get rid of the [ ] and the comma? and have it write..
a b c
d e f
and so on? because right now it's still printing to the file like this.. [ a b c , d e f ]
> Ok, i made it implement Serializable, the file has
> something, but it's not readable
I already told you--serialized data is not meant to be human readable.
>, is there a way to
> get rid of the [ ] and the comma? and have it
Yes. Create your own format for writing and reading it.
jverda at 2007-7-29 11:38:30 >

Yes i understand it's not read by humans, as for the toString, it's calling my BookMaintenance toString..
public String toString() {
return " "+title +" "+ author +" "+ publisher+" ";
}
How else would i write it?
i tried
System.out.println(super.toString());
but nope.
writing to file
[ 1 1 1 , 2 2 2 ]
reading from file
[ 1 1 1 , 2 2 2 ]
Now if i only knew how to not have it print out the arraylist tostring and write properly to a file
File f = new File("input111.txt");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
System.out.println("writing to file");
System.out.println(book);
oos.writeObject(book);
oos.close();
FileInputStream fin = new FileInputStream("input111.txt");
ObjectInputStream ois = new ObjectInputStream(fin);
ArrayList readList = (ArrayList)ois.readObject();
ois.close();
System.out.println("reading from file");
System.out.println(readList);
Are you printing the list or calling its (not your class') toString somewhere?
When you say you get [1, 2, 3] or whatever, you haven't given enough context.
I think you need to slow down, step back, and solve one part of your problem at a time. You seem to just be flobbering around, tossing off random code and then asking fo help for every little problem that comes up. You'll never get anything done or learn anything this way.
jverda at 2007-7-29 11:38:30 >

> You seem to just be flobbering around, tossing off...
That's quite a turn of the phrase, Mr. J.
~
I understand everything that it's doing. I'm not calling the ArrayList toString anywhere. As for the [ 1 2 3 ] the 1 2 3 are the values i input into the GUI when i push add.
Stop.
Are you trying to write output to a file to be read by a human?
Are you trying to write output to a file to be read by a computer?
Both?
~
Well i want it to write it to a file then when i open it, to read the contents of the file back into the GUI JTextFields.
> Well i want it to write it to a file then when i open
> it, to read the contents of the file back into the
> GUI JTextFields.
Very well. Don't worry about what the output looks like in the file. Just read the file contents back in as an object(s) (i.e., de-serialize them, assuming you serialized them in the first place), and use the object's data to populate the text fields.
~
Thats the stage i'm at. I'm printing off the values in the terminal but it's bringing up the [ ] and comma's which won't be friendly when i want to bring the tokens into the JTextFields.
> Now if i only knew how to not have it print out the
> arraylist tostring and write properly to a file
It is writing properly.
Look, what are you trying to do? You want to write it to a file, and then have your program read it again later? Then you don't care what format it's in. Just test it by writing it, reading it back, and making sure you end up with the same objects you started with.
If you want the file to be readable by humans, then the simplest think is java.beans.XMLEncoder. Humans can read it and you can use XMLDecoder to read it back into your program.
If you don't like that format, then *you* decide what format you want, and *you* write the code to write it out and read it in in that format.
jverda at 2007-7-29 11:38:35 >

> > You seem to just be flobbering around, tossing
> off...
>
> That's quite a turn of the phrase, Mr. J.
>
> ~
It was chosen quite deliberately.
jverda at 2007-7-29 11:38:35 >

Okay, how about this. The arraylist is written to a file, now i want it to read and get to be displayed back into the JTextFields.. Thats it, i can careless how it looks in the file, how it's written, i only care about it working.
> Thats the stage i'm at. I'm printing off the values
> in the terminal but it's bringing up the [ ] and
> comma's which won't be friendly when i want to bring
> the tokens into the JTextFields.
You're really not communicating well at all here.
Show actual code--just enough to show the whole problem, but no more.
If you're printing the list, then you are calling list's toString. If you don't like that format, then don't print the list. Instead, print the individual elements.
I can't deal with this any more. Good luck.
jverda at 2007-7-29 11:38:35 >

> Okay, how about this. The arraylist is written to a
> file, now i want it to read and get to be displayed
> back into the JTextFields..
Stop.
Two thigs.
Read it.
Display it in JTextField.
First do one. Then the oher. They are two completely unrelated things. Which one are you having problems with and exactly what probems are you having?
> Thats it, i can careless
> how it looks in the file,
That's right. You don't care how it looks in the file. But you've been making it soud like you do, or like it's not writing to the file correctly.
Please, for the love of god, be more detailed and precise.
jverda at 2007-7-29 11:38:35 >

Sorry i thought the printing into the file mattered. I thought when reading that i would have to use StringTokenizer and that would take in the brackets and commas aswell as the values. I thought that if i read it and display it back into the gui that it would display the [1 as a value and etc.
Now, as for reading it, it is reading it. I dont need to use StringTokenizer at all right?
I don't know how to get it back into the JTextFields though.
Jverd, sorry for pissing you off, i don't mean to.
> Sorry i thought the printing into the file mattered.
What matters is that the method that writes it writes out all the relevant information, and that the method that reads it knows how to interpret that information. writeObject and readObject have been around a long time, so you can assume that they work if you call them correctly (which you wern't doing originally, since you didn't implement Serializable).
What doesn't matter is what that format is, or whether you, as a human, can read it. If the file will only be written and read by software, not humans, then all tha matters is that the software can understand it.
> I thought when reading that i would have to use
> StringTokenizer
No. That's for tokenizing a String. For instance, if you read a text file and you want to break it up a certain way.
Readobject is already written to do whatever it needs to do to break apart the contents written by writeObject and assemble them into objects. This is known as encapsulation. You don't care *HOW* write/readObject work, only what end results they produce.
> I thought that if i
> read it and display it back into the gui that it
> would display the [1 as a value and etc.
Again, do NOT lump "reading and displaying" together.
You read it back. This gives you the same list you started with.
Now you want to display it. The display part doesn't know whether that list was read from a file or is the original that you started out with. It's just a list. The display part has to know how to display that list, but where it came from is irrelevant. This divide-and-conquer approach is of crucial importance when writing any software. Live it.
> Now, as for reading it, it is reading it. I dont need
> to use StringTokenizer at all right?
That depends. What format is it in? What's going to process it after reading it? If you wrote it with writeObject, then read it with readObject, and you'll end up with the same objects you started with. That's what write/readObject are for.
> I don't know how to get it back into the JTextFields
> though.
Okay. Make sure you understand that this is a completely separate issue from writing/reading the file.
You need to write a small method that just takes a list and displays it. Doesn't matter where the list comes from. Your initial testing of this method will simply use a hardcoded list that you create right there in the test program.
This method may need to in turn be broken out into smaller helper methods, but from the standpoint of "things I want to do," displaying a list is one "thing", so write a method whose job it is to display a list.
> Jverd, sorry for pissing you off, i don't mean to.
No, it's okay. I know there's a lot to take in at once and it can be hard for a newbie to separate the pieces out. I just get frustrated easily at communication misfires.
jverda at 2007-7-29 11:38:35 >

>
> Okay. Make sure you understand that this is a
> completely separate issue from writing/reading the
> file.
>
> You need to write a small method that just takes a
> list and displays it. Doesn't matter where the list
> comes from. Your initial testing of this method will
> simply use a hardcoded list that you create right
> there in the test program.
>
> This method may need to in turn be broken out into
> smaller helper methods, but from the standpoint of
> "things I want to do," displaying a list is one
> "thing", so write a method whose job it is to display
> a list.
I don't know how to display the list. I'm so confused.
> I don't know how to display the list.
Okay. What have you tried and what problems did you have.
Post code. Just a tiny program with a main, a method to set up your text field or whatever, and a displayList method that takes your list as a parameter and display it. Main should call setupTextField (or whatever), create a hardcoded list, and then pass that list to displayList.
Do as much of that as you can and provide details about exactly what problems you're having. If there are error message, paste in the complete, exact message. If it works but doesn't behave as you want, describe your desired and observed behavior as precisely as you can.
When you post code, please use[code] and [/code] tags as described in Formatting tips on the message entry page. (http://forum.java.sun.com/help.jspa?sec=formatting) It makes it much easier to read.
jverda at 2007-7-29 11:38:35 >

> I don't know how to display the list.
Time to do the tutorials, especially the part covering:
1) collections
http://java.sun.com/docs/books/tutorial/collections/intro/index.html
2) for loops:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/for.html
I'm reading your post over and over and trying to even get a start going but it's not clicking, do you have any examples of this?
> I'm reading your post over and over and trying to even get a start going but it's not clicking...
It's only been four minutes. Give yourself some time.
~
> I'm reading your post over and over and trying to
> even get a start going but it's not clicking, do you
> have any examples of this?
Okay, again, divide and conquer.
"I don't know how to display the list in a JTextField."
Do you know how to display *anything* in a JTextField? If not, google for a swing tutorial, or look at the links somebody posted a couple of posts ago.
Do you know how to write a main that calls two methods? If so, do that. Those methods can just do nothing but system.out.pritln their names.
Do you know how to write a little program where main calls two methods, and how to display some simple thing in a text field, but don't know how to display the *list*?
If so, then do as much as you can, and then look at this:
http://java.sun.com/docs/books/tutorial/collections/
Don't say you can't even start. You obviously can, as you have written *some* Java code.
One piece at a time.
Do you know how to dsplay
jverda at 2007-7-29 11:38:40 >

I'm guessing something like this is displaying the lsit.
Iterator iterator = book.iterator();
while(iterator.hasNext())
{
System.out.println(iterator.next());
}
Right or wrong?
> I'm guessing something like this is displaying the
> lsit.
>
>Iterator iterator = book.iterator();
>while(iterator.hasNext())
>{
> System.out.println(iterator.next());
>
>
You're not listening.
You're getting ahead of yourself, and you're not breaking it down.
Displaying a list can be broken down into smaller parts:
1) for each item in the list, do something
2) display a single item.
Those two are completely independent of each other. Make sure you know how to do each one on its own. Then worry about combining them into "display the list."
Now, you mention System.out.println here, but previously you wanted to put something into a GUI. Println won't work for that.
BUT, if you want to test "doing something for each item in the list," println is a great way to test that.
jverda at 2007-7-29 11:38:40 >

> I'm guessing something like this is displaying the lsit.
Not in a text field. Here's an example of what jverd was asking for:
import java.util.*;
import javax.swing.*;
public class Foo {
// Just a tiny program with a main, a method to set up your text field or whatever,
// and a displayList method that takes your list as a parameter and display it.
// Main should call setupTextField (or whatever), create a hardcoded list, and
// then pass that list to displayList.
private JTextField textField;
public static void main(String[] args) {
Foo f = new Foo();
List list = Arrays.asList("one", "two", "three");
f.setupTextFieldOrWhatever();
f.displayList(list);
}
void setupTextFieldOrWhatever() {
this.textField = new JTextField(50);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this.textField);
f.pack();
f.setVisible(true);
}
void displayList(List list) {
String text = list.toString().replaceAll("[\\[\\]]", "");
this.textField.setText(text);
}
}
~
> String text =
> list.toString().replaceAll("[\\[\\]]", "");
> this.textField.setText(text);
Ye gods, no.
1) I don't want to dump regex on him yet.
2) Relying on toString's format and munging that is a bad idea, IMHO.
jverda at 2007-7-29 11:38:40 >

> Ye gods, no.
Just an example.
> 1) I don't want to dump regex on him yet.
> 2) Relying on toString's format and munging that is a
> bad idea, IMHO.
Fair enough. Again, it was just a quick example as to the type of SSCCE you were asking for and not intended as a cut-n-paste solution. I can't edit it now that you've replied, though, so you'll have to settle for a repost:
import java.util.*;
import javax.swing.*;
public class Foo {
// Just a tiny program with a main, a method to set up your text field or whatever,
// and a displayList method that takes your list as a parameter and display it.
// Main should call setupTextField (or whatever), create a hardcoded list, and
// then pass that list to displayList.
private JTextField textField;
public static void main(String[] args) {
Foo f = new Foo();
List list = Arrays.asList("one", "two", "three");
f.setupTextFieldOrWhatever();
f.displayList(list);
}
void setupTextFieldOrWhatever() {
this.textField = new JTextField(50);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this.textField);
f.pack();
f.setVisible(true);
}
void displayList(List list) {
this.textField.setText(list.toString());
}
}
~
> Here's an example of what jverd
> was asking for:
Denis,
Yes, what he said, mostly.
I disagree with part of yawmark's approach (though maybe he did that on purpose, to leave some work for you), and I think he put more in there than you initially should, but that's the idea.
Start with a tiny program--main plus two methods. Main first calls the method to set up the GUI. Then main calls the method to display the list.
If you know how to setup the GUI but not how to display the list, then the displayList method could just System.out.println("in display"). Or, if you know how to display one piece of text, but not the list, it could put "hello" in the text field.
The idea is to start with something small and simple that you know works, and to build on that piece by piece.
jverda at 2007-7-29 11:38:40 >

> You're getting ahead of yourself, and you're not
> breaking it down.
>
> Displaying a list can be broken down into smaller
> parts:
>
> 1) for each item in the list, do something
> 2) display a single item.
>
>
Can't i just save each hasNext to a variable and then add it to the arraylist using a loop?
Mhm, i need to get away from the computer, i'm not event hinking straight anymore, i'll be back in a bit.
> > Ye gods, no.
>
> Just an example.
>
Yeah, I figured.
I just didn't want the OP to take it too literally.
> > 1) I don't want to dump regex on him yet.
>
> > 2) Relying on toString's format and munging that is
> a
> > bad idea, IMHO.
>
> Fair enough. I can't edit it now that you've replied,
> though.
MWUAH HA HA! My evil plan is working!
The repost is almost exactly what I'd been envisioning for the OP's first attempt though.
jverda at 2007-7-29 11:38:40 >

> I disagree with part of yawmark's approach (though
> maybe he did that on purpose, to leave some work for
> you), and I think he put more in there than you
> initially should, but that's the idea.
The regex was there as a dirty way to show a CSV-style list. That's not where the focus of attention should be. Rather, I had hoped to show how to write a small class with a main method that initializes a text field and has the method jverd described. I didn't mean to inject confusion, and as such, I'll bow out of the thread.
Cheers.
~
> > You're getting ahead of yourself, and you're not
> > breaking it down.
> >
> > Displaying a list can be broken down into smaller
> > parts:
> >
> > 1) for each item in the list, do something
> > 2) display a single item.
> >
> >
> Can't i just save each hasNext to a variable and then
> add it to the arraylist using a loop?
I don't know what you mean. However:
1) It's already in the ArrayList, no?
2) Try it with code. If you can't get it to work, post your code and specific questions/prolems.
> Mhm, i need to get away from the computer, i'm not
> event hinking straight anymore, i'll be back in a bit.
Okay. Learning when to step away is also very important. :-)
jverda at 2007-7-29 11:38:40 >

> The regex was there as a dirty way to show a
> CSV-style list. That's not where the focus of
> attention should be. Rather, I had hoped to show how
> to write a small class with a main method that
> initializes a text field and has the method jverd
> described.
Understood.
For this OP, though, I just thought it'd be more instructive to start way small and take it in baby steps. Just a stylistic difference.
> I didn't mean to inject confusion, and as
> such, I'll bow out of the thread.
No need to do that. You're usually able to provide more succinct explanations and examples than I, and your input is always welcome.
jverda at 2007-7-29 11:38:40 >

Question.
I have the gui setup already in my BookMaintenance.java. And use:
new Entry().setVisible(true);
To get it working. Do i use that instead of f.setVisible(true)?
I'm kind of at a loss of words.
Is there any other easier way to do this?
Well it reads and displays the list, Now how can i make it use my GUI and have it display in the right spot?
public static void main(String[] args) throws Exception{
FileInputStream fin = new FileInputStream("input111.txt");
ObjectInputStream ois = new ObjectInputStream(fin);
ArrayList readList = (ArrayList)ois.readObject();
ois.close();
System.out.println("reading from file");
System.out.println(readList);
Foo f = new Foo();
List list = Arrays.asList(readList);
f.setupTextFieldOrWhatever();
f.displayList(list);
}
void setupTextFieldOrWhatever() {
this.textField = new JTextField(50);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this.textField);
f.pack();
f.setVisible(true);
}
void displayList(List list) {
this.textField.setText(list.toString());
}
}
I don't know anything about GUIs, so I can't help you there. You might want to start a new thread in the swing forum if you have GUI specific quetsions.
As to whether something would work, the best way to answer that is to try it.
jverda at 2007-7-29 11:38:45 >

I have my gui setup. It's just a matter of connecting them. I need to open the GUI in my other class (with the main) and have it bring in the values correctly. I can create a new object and have it open but i don't know how to store the variables correctly.
Entry e = new Entry
e.setVisible(true);
private JLabel titleLabel;
private JLabel authorLabel;
private JLabel publisherLabel;
private JTextField titleField;
private JTextField authorField;
private JTextField publisherField;
private JButton addButton;
private JButton exitButton;
private JButton firstButton;
private JButton lastButton;
private JButton prevButton;
private JButton nextButton;
private JButton updateButton;
private JButton deleteButton;
private ArrayList<BookMaintenance> book;
private int currIndex = 0;
public Entry() {
initComponents();
}
private void initComponents() {
titleLabel = new JLabel("Title:");
authorLabel = new JLabel("Author:");
publisherLabel = new JLabel("Publisher:");
titleField = new JTextField();
authorField = new JTextField();
publisherField = new JTextField();
addButton = new JButton("Add");
exitButton = new JButton("Exit");
firstButton = new JButton("First");
lastButton = new JButton("Last");
prevButton = new JButton("Prev");
nextButton = new JButton("Next");
updateButton = new JButton("Update");
deleteButton = new JButton("Delete");
book = new ArrayList<BookMaintenance>();
JMenuItem openJMenu = new JMenuItem("Open...");
JMenuItem saveAsJMenu = new JMenuItem("Save As...");
JMenuItem exitJMenu = new JMenuItem("Exit");
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
JMenu dialogMenu = new JMenu("File");
bar.add(dialogMenu);
dialogMenu.add(openJMenu);
dialogMenu.addSeparator();
dialogMenu.add(saveAsJMenu);
dialogMenu.addSeparator();
dialogMenu.add(exitJMenu);
titleLabel.setSize(100, 20);
authorLabel.setSize(100, 20);
publisherLabel.setSize(100, 20);
titleField.setSize(200, 20);
authorField.setSize(200, 20);
publisherField.setSize(200, 20);
addButton.setSize(80, 20);
firstButton.setSize(65,20);
nextButton.setSize(65,20);
prevButton.setSize(65,20);
lastButton.setSize(65,20);
exitButton.setSize(65,20);
updateButton.setSize(74,20);
deleteButton.setSize(74,20);
titleLabel.setLocation(5, 5);
authorLabel.setLocation(5, 30);
publisherLabel.setLocation(5, 55);
titleField.setLocation(65, 5);
authorField.setLocation(65, 30);
publisherField.setLocation(65, 55);
addButton.setLocation(5, 80);
updateButton.setLocation(90, 80);
deleteButton.setLocation(169, 80);
exitButton.setLocation(248, 80);
firstButton.setLocation(15, 105);
prevButton.setLocation(155, 105);
nextButton.setLocation(85, 105);
lastButton.setLocation(225, 105);
this.getContentPane().setLayout(null);
this.getContentPane().add(titleLabel);
this.getContentPane().add(authorLabel);
this.getContentPane().add(publisherLabel);
this.getContentPane().add(titleField);
this.getContentPane().add(authorField);
this.getContentPane().add(publisherField);
this.getContentPane().add(firstButton);
this.getContentPane().add(nextButton);
this.getContentPane().add(prevButton);
this.getContentPane().add(lastButton);
this.getContentPane().add(exitButton);
this.getContentPane().add(addButton);
this.getContentPane().add(deleteButton);
this.getContentPane().add(updateButton);
this.pack();
this.setSize(326, 215);
this.setLocationRelativeTo(null);
this.setTitle("Book Maintenance");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
> Is there any other easier way to do this?
Unquestionably, yes.
~
> > Is there any other easier way to do this?
>
> Unquestionably, yes.
>
> ~
Please.. go on?
This doesn't work. Help?
ArrayList book;
BookMaintenance bookMaint;
String fileName="dataFile.txt";
FileInputStream in = new FileInputStream(fileName);
ObjectInputStream s = new ObjectInputStream(in);
book = (ArrayList)s.readObject();
//Now loop the arraylist and put it into the windowpane
for(int i=0;i < book.size();i++){
bookMaint = book.get(i);
titleField = bookMaint.getTitle();
authorField = bookMaint.getAuthor();
publisherField = bookMaint.getPublisher();
}
> This doesn't work. Help?
"Doesn't work" is defined as causing a miniature donkey to flatulate in your direction every time you run your application. If this isn't your problem then please be a bit more specific (e.g., providing an error message, etc.). It's probably a type problem, but you haven't provided enough detail to make troubleshooting anything other than guesswork.
~
> > This doesn't work. Help?
>
> "Doesn't work" is defined as causing a miniature
> donkey to flatulate in your direction every time you
> run your application. If this isn't your problem then
> please be a bit more specific (e.g., providing an
> error message, etc.). It's probably a type problem,
> but you haven't provided enough detail to make
> troubleshooting anything other than guesswork.
>
> ~
lol!
BookMaintenance.java:299: incompatible types
found: java.lang.Object
required: BookMaintenance
bookMaint = book.get(i);
^
BookMaintenance.java:300: incompatible types
found: java.lang.String
required: javax.swing.JTextField
titleField = bookMaint.getTitle();
^
BookMaintenance.java:301: incompatible types
found: java.lang.String
required: javax.swing.JTextField
authorField = bookMaint.getAuthor();
^
BookMaintenance.java:302: incompatible types
found: java.lang.String
required: javax.swing.JTextField
publisherField = bookMaint.getPublisher();
^
4 errors
Press any key to continue . . .
> 4 errors
> Press any key to continue . . .
Great. Now I can't find the "any" key...
Did you read the error messages? They tell you exactly what's wrong. What exactly do you not understand about, say, "found : java.lang.Object required: BookMaintenance"?
jverda at 2007-7-29 11:38:45 >

1) Casting.
2) Generics.
jverda at 2007-7-29 11:38:45 >

I read the error msg, i know what it wants, but then again i don't? Does that make sense? :S
get(i) returns a reference to Object. The compiler doesn't know that what you'll actually stick into and get out of the list is a BookThingy.
// casting
BookThingy bt = (BookThingy)list.get(i);
// generics, with enhanced for loop
List<BookThingy> list = new ArrayList<BookThingy>();
...
for (BookThingy bt : list) {
bt.doBookThingyStuff();
}
Use an iterator or enhanced for loop, NOT get(i).
http://java.sun.com/docs/books/tutorial/collections/
http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html
http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html
You don't have to use generics and enhanced for, but they can make your code more readable and, in the case of generics, more typesafe.
jverda at 2007-7-29 11:38:45 >
