2016-04-13 28 views
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()); 
+0

ItemListenerを使用することを忘れないでください。 Btwファイル 'ChildNames.txt'に15個以上のエントリがある場合、' readFiles'クラスは 'ArrayIndexOutOfBoundsException'をスローします。 – ArcticLord

+0

@ArcticLord理想的には、新しいエントリがテキストファイルに追加されたとき、15エントリを超えていても配列に追加されます。しかし確かではない? –

+0

いいえ。アレイには15個のエントリしか格納できません。そして、読み込まれた名前ごとにインデックスが増加します。 16番目の名前はインデックス15に格納され、例外が発生します。おそらく配列の代わりに 'List'を使うべきでしょう。 – ArcticLord

答えて

0

あなたはJComboBox#getSelectedItem()代わりにJComboBox#getSelectedIndex()を必要としています。それは文字列なので、ファイル内に出力する必要があります。

現在選択されている項目を返します。

は、あなたが選択した項目は `JComboBox.getSelectedItem`なく` JComboBox.getSelectedIndex`を使用取得したい場合は、あなたのJComboBox

関連する問題