java - 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);
}
解决方案
每当我遇到这些类型的问题时,我倾向于编写包装类或扩展原始类。例如,您可以执行以下操作:
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();
}
}
扩展通常是更简洁的解决方案,但我同时提供了这两种解决方案,因为您最终会遇到“最终”且无法扩展的类。
推荐阅读
- python - 带有预训练 resnet50 的中间层错误张量流
- python - cv2 视频在处理时未使用 imshow 显示
- reactjs - React Redux 无法创建持久存储
- node.js - 在 vscode 中调试节点时获取未绑定的断点
- android - 通过意图启动应用程序然后按返回按钮也会关闭父应用程序
- laravel - 我在 laravel 5.8 应用程序中安装 guzzlehttp/guzzle 时出错
- c++ - 我们如何使用循环展开和代码预加载为 C++ 程序编写优化的 ARM 代码?
- javascript - 将 Segment API 与 Chrome 扩展一起使用
- c# - 是否有在并发环境中跨多个渠道处理 RabbitMq 发布者确认的最佳实践?
- excel - 使用 Active.cell.column 和行范围的 VBA 范围