【问题标题】:static JComboBox not displaying in GUI静态 JComboBox 不在 GUI 中显示
【发布时间】:2012-03-13 12:05:15
【问题描述】:

我需要从多个类中访问 goToTop 和 discCrop 方法,因为我需要使用同一个 plantList JComboBox 实例,所以我尝试将其设为静态。但是当我运行下面的代码时,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();
}

}

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖SSCCE

标签: java user-interface static jcombobox swingx


【解决方案1】:

问题是您的 ComboBox 是静态的,并且您将其添加到非静态构造函数中的 JPanel 中,这不会产生任何问题并将 UI 组件添加到 JFrame 或任何父组件。事情是您用于 JCombobox 的数据或模型在某些情况下也需要是静态的,以便显示。

【讨论】:

  • 驱动这个模型的数组是静态的,从数据库中检索数据的方法也是静态的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-10
  • 2021-03-14
  • 2012-06-05
  • 1970-01-01
  • 2015-09-03
  • 1970-01-01
相关资源
最近更新 更多