[英]How can i load data from text file to Jlist in java swing?
我正在学习Java。 单击JButton将文本文件中的数据加载到JList时遇到麻烦,但是它注意到错误“ java.lang.NumberFormatException:对于输入字符串:“”。 首先,我将数据从4 JTextField输入到JList,然后保存文件文本。 我的txt文件的内容为:1-java-3-4。 请有人帮我。 谢谢。 这是我的代码按钮保存和加载数据:
private void btAddBookActionPerformed(java.awt.event.ActionEvent evt) {
String BookId = txtBookID.getText();
String BookName = txtBookName.getText();
String Quantity = txtQuantity.getText();
String Price = txtPrice.getText();
if(BookId.equals("")|| BookId.equalsIgnoreCase("Type Here") || BookName.equals("")|| BookName.equalsIgnoreCase("Type Here") || Quantity.equals("")|| Quantity.equalsIgnoreCase("Type Here")||Price.equals("")|| Price.equalsIgnoreCase("Type Here")){
txtBookID.setText("Type Here");
txtBookName.setText("Type Here");
txtPrice.setText("Type Here");
txtQuantity.setText("Type Here");
}else{
listmodel.addElement(BookId+"-"+BookName+"-"+Quantity+"-
"+Price);
booklist.setModel(listmodel);
txtBookID.setText("");
txtBookName.setText("");
txtQuantity.setText("");
txtPrice.setText("");
}
private void btLoadDBActionPerformed(java.awt.event.ActionEvent evt) {
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader("BookList.txt"));
int val = Integer.parseInt(br.readLine());
for (int i = 0; i < val; i++) {
String ss = br.readLine();
listmodel.addElement(ss);
}
booklist.setModel(listmodel);
}
catch(Exception e){
System.out.println(""+e);
}
finally{
try{
br.close();
}
catch(Exception e){
System.out.println(""+e);
}
}
}
仔细看一下代码,似乎根本不需要整数解析。 问题在于您正在以错误的方式读取文件。 代替for
循环,一种用于逐行读取文本文件(当您不知道文件的确切大小时)的常见用法是带有while
循环,如下所示:
br = new BufferedReader(new FileReader("BookList.txt"));
String line;
while ((line = br.readLine()) != null) {
listmodel.addElement(line);
}
booklist.setModel(listmodel);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.