[英]Read the first word of each line from a text file and then populate to Combo box
我有一個大學項目,我必須從文本文件中讀取每一行的第一個單詞,如下所示:
23123123213 Samuel classA
23423423423 Gina classC
23423423423 John classD
我可以通過3 JTextField
更新文本文件。
但現在我必須用所有行的第一個字(23123123213,23423423423和23423423423)填充JCombobox
。
我是java的新手,我甚至沒有提示如何做到這一點。 我知道如何讀寫文本文件。
請有人幫我這樣做嗎?
到目前為止我想出的代碼如下:
import java.io.*;
public class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("RokFile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
String[] delims = strLine.split(" ");
String first = delims[0];
System.out.println("First word: "+first);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
隨着你們的幫助,我成功地從每一行中提取了第一個字符串,但現在我怎么能在Jcombobox中填充它,我的意思是我應該先將它保存在某個地方?
提前致謝
如果您知道如何從文本文件中讀取行,則可以使用String.split函數將每行除以分隔符。 在這種情況下,你得到一個數組,你可以用一個普通的數組索引器得到第一個字符串,即[]運算符。
String hello = "Hello world";
String[] delims = hello.split(" ");
String first = delims[0];
要回答編輯,可以使用其構造函數填充JComboBox,例如采用Object數組的構造函數,或使用JComboBox.addItem(Object)函數。
后者有一個例子。 關於具有構造函數的那個,您可以自己構建一個對象數組,或者使用一個arraylist來添加所有元素,然后使用ArrayList.toArray()函數獲取一個數組。
您可以使用String.split()
或使用indexOf
和substring
來獲取第一個單詞。
有一個關於JComboBox的教程 。 Java Swing類基於Model / View,因此您必須將字符串填充到JCombobox的Model中。
編輯:為了響應您的編輯,假設您已檢索到值。 然后,您確實可以將它們保存到特定的數據結構中。 最好將檢索這些值的代碼放入一個單獨的方法中。 然后可以將從該方法返回的值(例如,List <String>)放入JComboBox中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.