Skip to content
Advertisement

How can i get specific column from csv file and put that items of column into jComboBox using java?

part of my code is here:

private void toCombo()
    {
    
    String data="C:\Users\Berk\Documents\NetBeansProjects\Getränklist.csv";
    String line="";
   
    try
    { 
    BufferedReader br=new BufferedReader(new FileReader(data));
    while((line=br.readLine())!=null)
            {   
  
                String[] record=line.split(",");            
                System.out.println(record[1]); //i can get column here              
                DefaultComboBoxModel model=new DefaultComboBoxModel(record); // but here i cant get column bcz record[1] doesnt accepted by compiler.
//as a matter of fact only last line appears in ComboBox. 
                    cmb.setModel(model);
                }
        }
        catch(FileNotFoundException e1)
        {
            e1.printStackTrace();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        }

i am pretty novice in Java and can’t do the thing that i want. for example i wanna get all items from 2. column and set them into ComboBox. I tried many things, searched many sites but failed. If somebody can help me i’d be much appreciated. here you can see my output:

England        Turkey         Germany        
India          China          Japan          
USA            Canada         Poland         
Holland        France         Spain          

Turkey
China
Canada
France

Advertisement

Answer

The JComboBox already have a ComboBoxModel. There is no need for you to create another one.

In your while loop all you need is:

comboBox.addItem( record[1] );

I tried many things, searched many sites but failed

Start with the basics from the Swing tutorial. Read the section from the Swing tutorial on How to Use Combo Boxes for more information.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement