1

I have 2 words ("Jakarta", "Bandung" ) in a CSV file that i want to retrieve and put it in the combobox. I can get those words, but based on my code, i will get every Jakarta and Bandung word, while i only want to retrieve it once per word. And i tried to put it in the combobox, but somehow it won't show up. This is my code so far.

public int a;
public String location;
public String destination;

private void formWindowOpened(java.awt.event.WindowEvent evt) { 

        String csvFile = "C:\\Users\\USER\\Desktop\\Project Data.csv";
        BufferedReader br = null;
        LineNumberReader reader = null;
        String line = "";
        String cvsSplitBy = ",";

        br = new BufferedReader(new FileReader(csvFile));
        reader = new LineNumberReader(new FileReader(csvFile));
        while ((reader.readLine()) != null);{
            a = reader.getLineNumber();
        }
        reader.close();

        while ((line = br.readLine()) != null) {

            String[] data = line.split(cvsSplitBy);
            location = data[1];
            destination = data[2];
        }

        int i;
        for(i = 0; i < a; i++){

        if(location.equals("Jakarta")){
            cmb1.addItem("Jakarta");
        }
}

Edit :

i tried another method using scanner, still no luck. Here is the code

String csvFile = "C:\\Users\\USER\\Desktop\\Project Data.csv";
        Scanner sc = new Scanner(new File(csvFile));
        while(sc.hasNext()){
            String word = sc.next();
            if(word.equalsIgnoreCase("Jakarta")){
                cmb1.addItem("Jakarta");
                JOptionPane.showMessageDialog(null, "Jakarta");
                break;
            }
        }
  • I suggest you adopt a Java-8 approach to your solution: https://www.mkyong.com/java8/java-8-stream-read-a-file-line-by-line/ Oh, and `location == "Jakarta"` is a big No-NO. Use `"Jakarta".equalsIgnoreCase(location)` instead. Good Luck Kevin. – Rann Lifshitz Jun 15 '18 at 05:06
  • i tried to add something to the combobox using the code without taking it from the file first. It's working. so i think the problem is within the code itself – Kevin Guswanto Jun 15 '18 at 06:06
  • as for the Java 8 stream reader. i don't fully understand how to get certain word with it. But may i know why you suggested to use it ? – Kevin Guswanto Jun 15 '18 at 06:07
  • Sure. Working with the Java-8 Files API removes the need to handle multiple readers/InputStreams and allows you to use the very powerful Java-8 Stream API for further data processing. – Rann Lifshitz Jun 15 '18 at 06:12
  • Did a little reading on JComboBox here : https://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html 1. Did you create a `ComboBoxRenderer` and set it as your combobox's renderer? 2. Since you are using the `addItem` method: These methods require that the combo box's data model be an instance of `MutableComboBoxModel`. Is this the case? – Rann Lifshitz Jun 15 '18 at 06:36

0 Answers0