Click to See Complete Forum and Search --> : Combobox, writes to file
MarkY
December 13th, 2001, 03:36 PM
New java programmer here. Thanks for any help.
I'm using a JCombobox (editable) that will allow a user to input an IP address OR select an IP address from a previously entered session. I would like the combobox to keep track of the last 5 addresses.
I'm having a difficult time figuring out how to create, open, and read/write to a file using the combobox.
So far:
x.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e)
{
Iaddress = (String) ((JComboBox)e.getSource()).getSelectedItem();
if ( Iaddress != null)
{
Iaddress = Iaddress.trim();
if (Iaddress.length() == 0)
Iaddress = null;
}
}
};
How do I create a file and add Iaddress to it. I will then read the file and populate the JComboBox with the addresses in the file.
Thanks for any help
Norm
December 13th, 2001, 06:26 PM
Separate your problem into its parts. First figure out how to write to a file, then read from it, then how to parse the input and put it into the combobox.
To write and read a file, there are several classes you can
use. For example the FileWriter would do for Strings. Wrap it in a BufferedWriter to have the write(String) method.
BufferedWriter br = new BufferedWriter(new FileWriter("theFile.txt"));
Then use the corresponding Reader classes to be able to read Strings from the file using reaadLine();
If you'll use the forum's Search you'll find better code examples on how to do this.
Then use the appropriate methods of the combobox to get the Strings from it to be written and to put the Strings into it after they are read. These would be in a loop controlled by the source of the Strings. When reading from the file, end of stream would end the loop. When reading from the combobox, the end of the list.
Norm
MarkY
December 14th, 2001, 01:22 PM
Thanks for the help. Additional questions....
I am now able to read and write to the file "history.txt".
What I haven't figured out is why my JCombobox will not populate more than the first "item", even when my file has three lines of IP addresses.
public void readIPhistory()
{
try
{
BufferedReader infile = new BufferedReader(new FileReader("history.txt"));
String line = infile.readLine();
while (line != null)
{
IPTGbox.addItem(line);
line = infile.readLine();
}
infile.close();
}
catch(Exception e){}
}
public void writeIPhistory(String ip)
{
try
{
FileWriter fwriter = new FileWriter("history.txt");
fwriter.write(ip);
fwriter.close();
}
catch(Exception e){}
}
Also, is there a way to tell if this "history.txt" file already exists?
Thanks for any help.
dlorde
December 14th, 2001, 04:41 PM
Also, is there a way to tell if this "history.txt" file already exists?
Catch the FileNotFoundException.
Dave
Norm
December 14th, 2001, 06:33 PM
I don't know what is in the history.txt file. Add a System.out.println(line) statement in the loop to see what the value of line is to be sure you are reading all the lines.
What is in the history.txt file after you execute the writeIPHistory() method? Have you looked? Does the String that is written have more than one line in it?
Use the File class exists() method to see if a file exists.
Norm
MarkY
December 14th, 2001, 06:45 PM
The history.txt file looks good. It contains:
123.123.123.123
130.131.28.1
140.141.110.3
I stepped through the code using a debugger and the file is being read correctly, i.e. one line at a time. The variable "line" changes to reflect each IP address. Once all of the lines in the file are read, the loop stops, but ALL lines are being read correctly.
Someone was telling me that the JcomboBox sometimes has problems with String objects and I might have to use a vector. Does this make sense? Any ideas about how I would use a vector in this case?
I got the file exists problem corrected.
Thanks for your help.
dlorde
December 14th, 2001, 07:30 PM
The readIPhistory() code works fine here, as long as the history.txt file has the IP addresses on separate lines. However, if you use the writeIPhistory(...) method to generate the file, it will concatenate all the IP addresses together (i.e. makes a single line) because no end-of-line characters are inserted between them.
Dave
Norm
December 15th, 2001, 09:44 AM
Ok, you have the read code working, now how about the write code? You previous example code wrote only one string to the file. Was that string built with lineends between the lines?
You don't say.
And also what about your combobox? You haven't shown how you are using it other than the addItem() statement.
Have you read the doc for addItem()?
Adds an item to the item list. This method works only if the JComboBox uses the default data model. JComboBox uses the default data model when created with the empty constructor and no other model has been set.
Warning: Focus and keyboard navigation problems may arise if you add duplicate String objects. A workaround is to add new objects instead of String objects and make sure that the toString() method is defined. For example:
comboBox.addItem(makeObj("Item 1"));
comboBox.addItem(makeObj("Item 1"));
...
private Object makeObj(final String item) {
return new Object() { public String toString() { return item; } };
}
Parameters:
anObject - the Object to add to the list
Norm
MarkY
December 15th, 2001, 02:57 PM
Norm:
Thanks for your help. My code is at my office and I will post more info on Monday. I have read the doc for addItem().
I am only writing one line to the file. The current line that the user enters in the the editable combobox. However, I am opening the file in append mode, so the data is written to the end of the file. The data is being written OK, I have looked at the file in a text editor and all looks well.
I will post how I am using the combobox when I get back to the office.
Thanks again for your help.
Norm
December 15th, 2001, 06:27 PM
Yes, it would be better if you posted the actual code instead of ...
In looking at the code that was posted, I don't think it would compile:
FileWriter fwriter = new FileWriter("history.txt");
The FileWriter class is abstract and its constructor takes a Writer not a String!
Norm
Norm
December 15th, 2001, 06:41 PM
Please ignore my other message. I guess I need new eyeballs. I was reading the doc for FilterWriter, not FileWriter.
Norm
dlorde
December 16th, 2001, 12:40 PM
The FileWriter code compiles and works OK. You must be thinking of a different Writer...
FileWriter is a concrete convenience class for writing character files. Its constructor takes a File, a FileDescriptor, or a String file name (with or without boolean append flag).
Dave
Norm
December 16th, 2001, 08:48 PM
Yes, thanks. The print in my doc is too small. I've often seen FilterWriter as FileWriter. Not familiar enough with all the I/O classes to remember which are concrete and which not.
Another point, the posted code does not have the append flag set true, so I don't understand how the programmer is seeing the strings appended to the file, as he says they are?
Norm
dlorde
December 17th, 2001, 05:26 AM
Yes, the missing 'append' flag would certainly cause the symptom of only getting one line in the comboBox. I can only guess that the file that looks OK isn't the file being written and read by the application... It's happened to me before.
Dave
MarkY
December 17th, 2001, 09:49 AM
Below is the code (snipped a little for brievity) in question. I've added comments about opening the file in append mode. Also, I have verified that I am indeed reading the correct file. When I read the file in a text editor, the IP addresses are indeed on single lines. They are not concatnated.
Thanks again for all your help. I cannot figure out why only the first line of the history.txt file is populated in the combobox. When I walk through the code using a debugger, ALL the lines of the file are read. Everything looks good.
Thanks again for your help.
package Communication;
/*
A basic extension of the java.awt.Dialog class
*/
import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.filechooser.*;
public class IpAddressDialog extends Dialog
implements TimeListener,
ActionListener
{
String serverIP;
//JTextField ipTxtFld;
JComboBox IPTGbox = new javax.swing.JComboBox();
protected WindowListener wl;
String IPTGaddress;
public IpAddressDialog(Frame parent)
{
super(parent);
thisParent = parent;
openBtn = new JButton();
openBtn.setText("Open Session");
openBtn.addActionListener(this);
panel1.add(openBtn);
exitBtn = new JButton();
exitBtn.setText("Exit");
exitBtn.addActionListener(this);
panel1.add(exitBtn);
exitBtn.setBounds(178,80,120,40);
setTitle("Connect To Server");
//IPTGbox
IPTGbox.setMaximumRowCount(5);
IPTGbox.setEditable(true);
//READ the HISTORY file befor opening frame
readIPhistory();
panel1.add(IPTGbox);
IPTGbox.setBounds(72,24,168,28);
//action Listener for ComboBox
IPTGbox.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
IPTGaddress = (String)((JComboBox)e.getSource()).getSelectedItem();
System.out.println(IPTGaddress);
if (IPTGaddress != null)
{
IPTGaddress = IPTGaddress.trim();
if (IPTGaddress.length() == 0)
{
IPTGaddress = null;
}
}
}
});
if (Connection.getConnectionStatus() == true)
{
IPTGbox.setEditable(false);
openBtn.setEnabled(false);
try
{
thisParent.setTitle("IP Traffic Generator " + dgram.getInstance().getHostAddressString());
}
catch (Exception err) {err.printStackTrace();}
}
addWindowListener(wl = new WindowAdapter()
{
public void windowActivated(WindowEvent event)
{
Object object = event.getSource();
}
public void windowClosing(WindowEvent event)
{
Object object = event.getSource();
if (object == IpAddressDialog.this)
IpAddressDialog_WindowClosing(event);
}
});
}
public IpAddressDialog(Frame parent, boolean modal)
{
this(parent);
setModal(modal);
}
//IPTGbox
//READING HISTORY.TXT here
public void readIPhistory()
{
try
{
BufferedReader infile = new BufferedReader(new FileReader("history.txt"));
String line = infile.readLine();
while (line != null)
{
IPTGbox.addItem(line); //**** THIS IS THE LINE that doesn't seem to be working ****
line = infile.readLine();
}
infile.close();
}
catch(Exception e){}
}
// WRITING HISTORY.TXT here
public void writeIPhistory(String ip)
{
try
{
// OPEN FILE **** Notice boolean set to TRUE ****
FileWriter fileWriter = new FileWriter("history.txt",true);
fileWriter.write(ip + "\n");
fileWriter.close();
}
catch(Exception e){}
}
public void actionPerformed(java.awt.event.ActionEvent event)
{
Object object = event.getSource();
if (object == openBtn)
openBtn_ActionPerformed(event);
else if (object == exitBtn)
exitBtn_ActionPerformed(event);
}
void openBtn_ActionPerformed(java.awt.event.ActionEvent event)
{
InetAddress inet;
String validIp = null;
int timeDelay = 1100;
connectTimer = new Timer(this);
connectTimer.setDelay(timeDelay);
serverIP = IPTGaddress;
writeIPhistory(serverIP); //WRITE the IPaddress entered
//serverIP = ipTxtFld.getText();
try
{
inet = InetAddress.getByName(serverIP);
validIp = inet.getHostAddress();
} catch (Exception e)
{
System.err.println(e);
}
if (!serverIP.equals(validIp))
{
JOptionPane.showMessageDialog(null,"Please enter a valid IP Address.");
}
else
{
try
{
client.getInstance().start(serverIP);
} catch (SocketException e) {}
//writeIPhistory(serverIP);
connectTimer.start();
}
}
}
dlorde
December 17th, 2001, 11:33 AM
Unfortunately, posting all that code doesn't really help, as it's incomplete and won't compile. However, the relevant bits (read/writeIPhistory) work fine in isolation. I inserted those two methods into a test application that had a comboBox and then made the following calls: writeIPhistory("String 1");
writeIPhistory("String 2");
writeIPhistory("String 3");
readIPhistory();
All the strings were inserted into the comboBox and displayed OK. Whatever the problem is, it isn't in those methods.
Dave
MarkY
December 17th, 2001, 12:14 PM
Thanks for the help. The code that I posted is small part of a java application that is about 5000 lines long, so there is no feasible way to post a compilable version.
However, do you think that it is possible that your test worked because you were using a "literal string" where as I'm using a String variable (line)?
Thanks again.
dlorde
December 17th, 2001, 12:18 PM
No, it should make no difference whether a literal string is used or a String reference. A String is automagically created from the literal before it can be passed to the method (as if you wrote method(new String("literal"));).
Dave
Norm
December 18th, 2001, 07:29 PM
Yes there is a way to shorten long programs with problems to demonstrate the problem, but it takes some work.
I took your almost useless piece of code(too many undefines) and have reworked it to a short program that reads from a file, populates a JComboBox and write extra lines to the file. It runs and there is no problem doing any of the above. The new lines show up in the combobox next time the program is run.
Which means that you must have a problem somewhere else in the remaining 5000 lines you didn't post.
Here's the reworked code:
import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class LoadingComboBox extends Dialog implements ActionListener {
final String DataFile = "LoadingComboBox.dat";
String serverIP;
JComboBox IPTGbox = new javax.swing.JComboBox();
protected WindowListener wl;
String IPTGaddress;
JButton openBtn, addBtn, exitBtn;
JPanel panel1 = new JPanel();
public LoadingComboBox(Frame parent) {
super(parent);
openBtn = new JButton();
openBtn.setText("Open Session");
openBtn.addActionListener(this);
panel1.add(openBtn);
addBtn = new JButton("Add a line");
addBtn.addActionListener(this);
panel1.add(addBtn);
exitBtn = new JButton();
exitBtn.setText("Exit");
exitBtn.addActionListener(this);
panel1.add(exitBtn);
exitBtn.setBounds(178,80,120,40);
setTitle("Connect To Server");
//IPTGbox
IPTGbox.setMaximumRowCount(5);
IPTGbox.setEditable(true);
//READ the HISTORY file befor opening frame
readIPhistory();
panel1.add(IPTGbox);
IPTGbox.setBounds(72,24,168,28);
//action Listener for ComboBox
IPTGbox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
IPTGaddress = (String)((JComboBox)e.getSource()).getSelectedItem();
System.out.println(IPTGaddress);
if (IPTGaddress != null){
IPTGaddress = IPTGaddress.trim();
if (IPTGaddress.length() == 0){
IPTGaddress = null;
}
}
}
});
addWindowListener(wl = new WindowAdapter(){
public void windowActivated(WindowEvent event){
Object object = event.getSource();
}
public void windowClosing(WindowEvent event){
Object object = event.getSource();
}
});
// I had to add the following 3 lines:
add(panel1);
setSize(300, 200);
setVisible(true);
} // end Constructor
public LoadingComboBox(Frame parent, boolean modal) {
this(parent);
setModal(modal);
}
//IPTGbox
//READING HISTORY.TXT here
public void readIPhistory(){
try {
BufferedReader infile = new BufferedReader(new FileReader(DataFile));
String line = infile.readLine();
while (line != null) {
System.out.println("adding line to cb " + line);
IPTGbox.addItem(line); //**** THIS IS THE LINE that doesn't seem to be working ****
line = infile.readLine();
}
infile.close();
}
catch(Exception e){}
}
// WRITING HISTORY.TXT here
public void writeIPhistory(String ip){
try {
// OPEN FILE **** Notice boolean set to TRUE ****
FileWriter fileWriter = new FileWriter(DataFile,true);
fileWriter.write(ip + "\n");
fileWriter.close();
} catch(Exception e){}
}
public void actionPerformed(java.awt.event.ActionEvent event) {
Object object = event.getSource();
if (object == openBtn)
openBtn_ActionPerformed(event);
else if (object == exitBtn){
System.exit(0);
}else if (object == addBtn) {
// Write a line to the history file
writeIPhistory("Added this at " + new java.util.Date());
}else {
System.out.println("unkn ae " + event);
}
}
void openBtn_ActionPerformed(java.awt.event.ActionEvent event) {
}
// FOllowing added for testing...................
public static void main(String[] args) {
// this frame sets size, location and traps closing
NormsTools.TestFrame tf = new NormsTools.TestFrame();
tf.show();
new LoadingComboBox(tf);
}
}
Norm
codeguru.com
Copyright WebMediaBrands Inc., All Rights Reserved.