1 Attachment(s)
Retrieving data from text file and putting it into comboboxes
Hi everyone im stuck with the part on trying to retrieve data from the textfile and then putting it into the combo boxes. I've uploaded my textfile as well. Can i know what's wrong with my code? In my text file there is
Apple,AA
Yahoo,YHOO
What i want to do is i wan to only show the words Apple and then Yahoo in my combo boxes any idea how to do that? Here's my code
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class StudNames {
public static void main(String[] args) {
ReadFromFile namesOfStocks= new ReadFromFile();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
StockFrame frame = new StockFrame("Stocks List");
frame.showGUI();
}
});
}
}
class StudFrame extends JFrame {
PanelWithComboBox panel = new PanelWithComboBox();
public StudFrame(String name) {
setTitle(name);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
add(panel);
}
public void showGUI() {
setVisible(true);
}
}
class PanelWithComboBox extends JPanel {
JComboBox comboBox;
ReadFromFile rff = new ReadFromFile();
public PanelWithComboBox() {
ArrayList<String> listOfStock = rff.getStock("/C:/Java Sem 2/FYP SEM 1/stocklist.txt");
comboBox = new JComboBox(listOfStock.toArray());
add(comboBox);
}
}
class ReadFromFile {
int indexOfNames = 0;
ArrayList<String> stockNames = new ArrayList<String>();
public ArrayList<String> getStock(String filename) {
BufferedReader reader = null;
try {
int positionOfTab = 0;
String lineOfString;
reader = new BufferedReader(new FileReader("/C:/Java Sem 2/FYP SEM 1/stocklist.txt"));
while((lineOfString = reader.readLine()) != null) {
positionOfTab = lineOfString.indexOf('\t');
if(positionOfTab > 0)
stockName.add(lineOfString.substring(0, positionOfTab));
else
stockName.add("");
}
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
return stockName;
}
}