2012-03-13 40 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