我有一个奇怪的(在我看来)问题。我目前正在为自定义渲染器中需要的一些自定义功能制作自定义 JComboBoxModel,我还不确定如何处理,稍后我将发布相关内容。
无论如何,正如标题所暗示的那样,我遇到了一些类型错误。
这是类(当前)代码:
package miscclasses;
import java.util.ArrayList;
import javax.swing.AbstractListModel;
public class CustomComboBoxModel<String> extends AbstractListModel<String> {
/**
* Contains a list of row indexes that shouldn't be displayed.
*/
private ArrayList<String> alreadySelectedIndexes;
/**
* The comboBoxes selected index.
*/
private int selectedIndex=-1;
/**
* Contains a list of values in this model.
*/
private ArrayList<String> vals;
/**
* Creates an empty CustomComboBoxModel.
*/
public CustomComboBoxModel() {
this.alreadySelectedIndexes=new ArrayList<>();
this.vals = new ArrayList<>();
}
/**Creates a CustomComboBoxModel with the values passed in.
*
* @param values the row values.
*/
public CustomComboBoxModel(ArrayList<String> values) {
this();
this.vals.addAll(values);
}
public CustomComboBoxModel(ArrayList<String> values, ArrayList<String> alreadySelected) {
this(values);
this.alreadySelectedIndexes.addAll(alreadySelected);
}
public CustomComboBoxModel(ArrayList<String> values, ArrayList<String> alreadySelected, int selectedIndex) {
this(values, alreadySelected);
this.selectedIndex=selectedIndex;
}
public CustomComboBoxModel(ArrayList<String> values, ArrayList<String> alreadySelected, String selectedValue) {
this(values, alreadySelected);
if(!this.vals.isEmpty()) {
//this.selectedIndex = Misc.containsI(this.vals, selectedValue);
}
}
@Override
public int getSize() {
return this.vals.size();
}
@Override
public String getElementAt(int i) {
return this.vals.get(i);
}
public boolean isRowSelected(int i) {
return ((!this.alreadySelectedIndexes.contains(Integer.toString(i)))?false:true);
}
}
我收到的错误在第 55 行,我尝试在其中获取所选值索引。这是构造函数中的注释行,它接受两个 ArrayList 列表和一个字符串值。该错误指出“没有适合的方法 containsI(java.util.ArrayList,String) 方法 miscclasses.Misc.containsI(java.util.ArrayList, java.lang.String) 不适用”。
据我所知 String 和 java.lang.String 是完全相同的东西。因此,我似乎无法弄清楚可能导致此问题的原因,并认为我会来问那些比我更了解 Code-fu 方式的人。
作为参考,Misc.containsI(ArrayList,String) 代码在这里:
/**
* Finds the index of value Target. Returns -1 if this ArrayList doesn't contain Target.
* @param a ArrayList of Strings a.
* @param target Value to find.
* @return Index of target if found; Else returns -1.
*/
public static int containsI(ArrayList<String> a, String target) {
for (int i = 0; i < a.size(); i++)
{
if(a.get(i).equalsIgnoreCase(target))
return i;
}
return -1;
}
我还奇怪地在我的 isRowSelected(int i) 函数中收到以下警告:“对 java.util.Collection.contains 的可疑调用:预期类型字符串,实际类型字符串”。
同样,我不明白为什么我会收到警告。它似乎是完全有效的代码,我之前也做过类似的事情。对于这个奇怪的警告和错误的任何帮助,将不胜感激。
编辑:更改声明,使其内容为:
public class CustomComboBoxModel extends AbstractListModel<String>
代替:
public class CustomComboBoxModel<String> extends AbstractListModel<String>
似乎已经摆脱了警告和错误。但是我不明白为什么,因为我声明了一个自定义 JList 模式:
public class CustomListModel<String> extends javax.swing.DefaultListModel<String>
在同一个包中没有错误。