0
配列のデータを含むコンボボックスがあります。 JComboBox
で選択した名前を取得し、それをテキストファイルに出力したいと考えています。問題は、名前がテキストファイルに書き込まれないということです。コンボボックスから選択項目を取得
アレイコード:
public class readfiles {
String [] names = new String[15];
int i = 0;
private Scanner readNames;
//Opens the file
public void openFile() {
try {
readNames = new Scanner(new File("ChildName.txt"));
} catch (Exception e) {
System.out.println("Could not locate the data file!");
}
}
//Reads the names in the file
public void readFile() {
while(readNames.hasNext()) {
names[i] = readNames.next();
System.out.println(names[i]);
i++;
}
}
//Closes the file
public void closeFile() {
readNames.close();
}
}
コンボボックスコード:
//JComboBox for selecting child
JLabel selectChildName = new JLabel("Please Select Your Child:");
sPanel.add(selectChildName);
readfiles readNames = new readfiles();
readNames.openFile();
readNames.readFile();
readNames.closeFile();
JComboBox<String> selectChild = new JComboBox<String>(readNames.names);
sPanel.add(selectChild);
そして最後に、これは私がテキストファイルに選択した名前を書くためにやっているものです。
bw.write(selectChild.getSelectedIndex());
使用し
UPDATE:
bw.write(selectChild.getSelectedItem().toString());
と
ItemListener
を使用することを忘れないでください。 Btwファイル 'ChildNames.txt'に15個以上のエントリがある場合、' readFiles'クラスは 'ArrayIndexOutOfBoundsException'をスローします。 – ArcticLord@ArcticLord理想的には、新しいエントリがテキストファイルに追加されたとき、15エントリを超えていても配列に追加されます。しかし確かではない? –
いいえ。アレイには15個のエントリしか格納できません。そして、読み込まれた名前ごとにインデックスが増加します。 16番目の名前はインデックス15に格納され、例外が発生します。おそらく配列の代わりに 'List'を使うべきでしょう。 – ArcticLord