Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to read a file in a combobox? The simple way.... 1

Status
Not open for further replies.

javaken

Technical User
May 15, 2004
20
BE
Suppose you have folowing persons.txt file with a list of persons:

0 John
1 Mary
2 Jenny
3 Michael
4 Jane

How to read this in a combobox java-swing?

Thanks!!!!
 
//assume there is one space between the number and the person 's name
//
import java.io.*;
import javax.swing.*;
import java.awt.*;
class ReadFile2 extends JFrame
{
final int MAXCHOICE = 100;
String myLine[], peopleName[];
int myInt[];
int count=0;
JComboBox jc;
public ReadFile2(String tempFile)
{
super("JComboBox Demo");
getContentPane().setLayout(new FlowLayout());
jc = new JComboBox();
getContentPane().add(jc);
int pos;
String tempStr;
myLine = new String[MAXCHOICE];
peopleName = new String[MAXCHOICE];
myInt = new int[MAXCHOICE];
File f = new File(tempFile);
try
{
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
myLine[count] = br.readLine();
while(count<=MAXCHOICE-1)
{
count++;
myLine[count] = br.readLine();
if (myLine[count]==null)
{
count--;
break;
}
}
br.close();
fr.close();

}
catch (Exception e)
{
}
for (int i=0;i<count;i++)
{
if (myLine!=null)
{
System.out.println(myLine);
pos = myLine.indexOf(" ");// search for position of space in each line
if (pos!=-1)
{
myInt = Integer.parseInt(myLine.substring(0,pos));
tempStr = "";
for (int x=pos; x<myLine.length(); x++)
{
tempStr+=myLine.charAt(x);
}
peopleName = tempStr;
}
jc.addItem(peopleName);
}
}
}
public static void main(String args[])
{
ReadFile2 rfObj = new ReadFile2("persons.txt");
rfObj.setSize(400,400);
rfObj.setVisible(true);
}
}
 
public static void main(String args[])
{
ReadFile2 rfObj = new ReadFile2("persons.txt");
rfObj.setSize(400,400);
rfObj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rfObj.setVisible(true);
}
// this will make the JFrame that can be close with a mouse click
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top