Home > database >  How do i get the particular data into the combo box from txt file in Java swing
How do i get the particular data into the combo box from txt file in Java swing

Time:08-17

I am currently working on an assignment that requires me to show the item inside the menu.txt to the user inside the combobox. And the data stored inside the menu.txt is like

1    Pizza     $50
2    CocaCola  $3
3    Rice      $1

The currently code that im using is :

    public void fillComboFromTxtFile(){
    File file = new File("Menu.txt");
    try{
        BufferedReader br = new BufferedReader(new FileReader(file));
        Object[] lines = br.lines().toArray();
        
        for (int i=0;i<lines.length;i  ){
            String line = lines[i].toString();
            cbName.addItem(line);
        }
        
    }catch(FileNotFoundException ex){
        Logger.getLogger(Order.class.getName()).log(Level.SEVERE,null,ex);
    }
    
}
        

But instead of showing the name of the food, the item listed inside the combo box is like

1Pizza$50
2CocaCola$3
3Rice$1

What I really want in my combo box is like only showing

Pizza
CocaCola
Rice

What am I suppose to do? Thanks

CodePudding user response:

You have also to split the line at the whitespaces and take the first element, because that is the name

    public void fillComboFromTxtFile(){
    File file = new File("Menu.txt");
    try{
        BufferedReader br = new BufferedReader(new FileReader(file));
        Object[] lines = br.lines().toArray();
        
        for (int i=0;i<lines.length;i  ){
            String line = lines[i].toString();
            cbName.addItem(line.split("\\s ")[1]);
        }
        
    }catch(FileNotFoundException ex){
        Logger.getLogger(Order.class.getName()).log(Level.SEVERE,null,ex);
    }
    
}
  • Related