2012-03-13 80 views
0

我需要從多個類訪問goToTop和discCrop方法,並且因爲我需要使用plantList JComboBox的同一個實例工作,所以我試圖使其成爲靜態。但是當我運行下面的代碼時,JComboBox不會顯示在GUI中。如果我將靜電消除,它會完美顯示。靜態JComboBox不顯示在GUI中

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.ArrayList; 

import javax.swing.JComboBox; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 

import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator; 

public class PlantList extends JPanel { 

private static final long serialVersionUID = 1L; 

static DBio getData = new DBio(); 
MinorMethods extMethod = new MinorMethods(); 

static ArrayList<String> plantIDs = new ArrayList<String>(getData.dataSetString("SELECT plantID FROM variety ORDER BY plantID")); 
static Object[] plantsObject = plantIDs.toArray(); 
static JComboBox plantList = new JComboBox(plantsObject); 

String oldID = ""; 

ActionListener comboListener = new ActionListener() { 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     if (oldID == "") { 
      oldID = plantList.getSelectedItem().toString(); 
      Launcher.repaintData(oldID); 
      MinorMethods.setCurrentID(oldID); 
     } else { 
      String newID = plantList.getSelectedItem().toString(); 
      if (newID != oldID) { 
       oldID = newID; 
       Launcher.repaintData(oldID); 
       MinorMethods.setCurrentID(oldID); 
      } 
     } 
    } 
}; 

public PlantList() { 
    setLayout(null); 
    AutoCompleteDecorator.decorate(plantList); 
    plantList.addActionListener(comboListener); 

    JLabel lbl = new JLabel("Choose Plant:"); 

    lbl.setBounds(1, 1, 84, 9); 
    plantList.setBounds(1, 17, 140, 22); 

    add(lbl); 
    add(plantList); 
} 

public void addNewPlant() { 
    plantList.insertItemAt(MinorMethods.getCurrentID(), 0); 
    goToTop(); 
} 

public static void goToTop() { 
    plantList.setSelectedIndex(0); 
} 

public static void discCrop() { 
    int currentIndex = plantList.getSelectedIndex(); 
    plantList.removeItemAt(currentIndex); 
    goToTop(); 
} 

}

+0

爲了更快提供更好的幫助,請發佈[SSCCE](http://sscce.org/)。 – 2012-03-13 14:39:35

回答

1

事情是你的組合框是靜態的,你是在構造函數也不是一成不變的,這不會產生任何問題,並增加了UI組件的JFrame或任何父組件將它添加到的JPanel。事情是你用於JCombobox的數據或模型在某些情況下也需要是靜態的,以便它被顯示。

+0

驅動此模型的陣列是靜態的,就像從數據庫中檢索數據的方法一樣。 – LiquidDrummer 2012-03-14 12:23:17