1

申し訳ありませんが、私はJavaの初心者ですが、変数petListをnullに設定せずに初期化するにはどうすればよいですか?

for (int x = 0;x<= buttonPressed;x++){

    println("adding box");
    String[] petStrings = { "Withdraw", "Deposit", "Blah", };

    //Create the combo box, select item at index 4.
    @SuppressWarnings({ "rawtypes", "unchecked" })
    JComboBox petList[] = null;// = new JComboBox(petStrings);
    petList[x] = new JComboBox(petStrings);
    petList[x].setSelectedIndex(1);
    petList[x].setBounds(119, (buttonPressed *20)+15, 261, 23);

    contentPane.add(petList[x]);        
}
4

2 に答える 2

3

配列を作成する際には、次の 3 つの点を考慮する必要があります。

  1. 宣言: JComboBox [] petList;
  2. 配列を初期化します。petList = new JComboBox[someSize];
  3. 割り当て: petList[i] = new JComboBox();

したがって、petList外側を取得しfor-loopます(インスタンス変数として定義する方が良いかもしれません):

public class YourClass{
//instance variables 
private JComboBox[] petList; // you just declared an array of petList
private static final int PET_SIZE = 4;// assuming
//Constructor
public YourClass(){
 petList = new JComboBox[PET_SIZE];  // here you initialed it
 for(int i = 0 ; i < petList.length; i++){
  //.......
  petList[i] = new JComboBox(); // here you assigned each index to avoid `NullPointerException`
 //........
 }
}}

注: これはコンパイルされたコードではなく、問題の解決方法を示しているだけです。

于 2013-08-02T23:40:36.643 に答える
2

ループする必要があります。これにより、境界の重複などの他のエラーが発生しますが、これが要点です。

JComboBox[] petList = new JComboBox[petStrings.length];
for(int i=0; i<petStrings.length; i++){
    petList[i]=new JComboBox(petStrings[i]);
}
于 2013-08-02T23:31:32.017 に答える