I need to access the goToTop and discCrop method from multiple classes, and since I need to work with the same instance of the plantList JComboBox I attempted to make it static. But when I run the code below, the JComboBox does not display in the GUI. If I take the static out, it displays perfectly.
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();
}
}
Thing is your ComboBox is static and you are adding it to JPanel in constructor which is not static, this does not create any issue and adds UI component to JFrame or any parent component. Thing is the data or model which you are using for JCombobox also needs to be static in some cases so that it gets shown.