简体   繁体   English

如何从 Java swing 中的 txt 文件中将特定数据放入组合框中

[英]How do i get the particular data into the combo box from txt file in Java swing

I am currently working on an assignment that requires me to show the item inside the menu.txt to the user inside the combobox.我目前正在处理一项任务,该任务要求我向 combobox 中的用户显示 menu.txt 中的项目。 And the data stored inside the menu.txt is like而menu.txt里面存储的数据就像

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谢谢

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);
    }
    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM