首页 > 解决方案 > JComboBox 将与泛型类型数组列表一起使用吗?

问题描述

我试图让我JComboBox使用通用数组列表。我这里的想法如下,我将使用这个draw()函数将不同类型的数组列表添加到我的 JPanel 中,而不是为不同类型的数组列表添加不同的函数。这可能吗?

我只是得到The constructor JComboBox<T>(ArrayList<T>) is undefined我认为是因为我没有按预期给 JBoxCombo 一个特定类型的错误?

public void draw(ArrayList<T> arrayList){

  //ERROR HERE (see description for error message)  
  JComboBox<T> ArrayListToJCombo = new JComboBox<T>(arrayList);

  //p1 (JPanel obj) initalized at the top of the class
  p1.add(ArrayListToJCombo);

  //frame (JFrame obj) inialized at the top of the class
  frame.add(p1);

  frame.setVisible(true);       

}

标签: java

解决方案


每当我遇到这些类型的问题时,我倾向于编写包装类或扩展原始类。例如,您可以执行以下操作:

public class MyJComboBox<T> extends JComboBox {
    ArrayList<T> list;
    public MyJComboBox<T>() {
        // Handle instantiation here, similar to what's done in JComboBox!
    }
}

或者

public class MyJComboBox<T> {

    JComboBox jcb;
    ArrayList<T> list;
    public MyJComboBox<T>() {
        // Handle T in here
        this.jcb = new JComboBox();
    }
}

扩展通常是更简洁的解决方案,但我同时提供了这两种解决方案,因为您最终会遇到“最终”且无法扩展的类。


推荐阅读