我很难扩展JComboBox。主要是,我希望添加一个将选定项返回到字符串中的方法。但是,由于以后我可能希望添加更多的方法,所以我决定最好创建一个子类。
import javax.swing.JComboBox;
public class ComboBox extends JComboBox{
public ComboBox(Integer[] items) {
super();
}
public ComboBox(String[] items) {
super();
}
public String getSelectedItemInString() {
return super.getSelectedItem().toString();
}
}以上是我的尝试,但不会是这样的。它只会创建这样的ComboBoxes,即使我单击下拉按钮结果,也无法看到这些项目。
我希望能够创建ComboBox,在不同的情况下可以同时接受String[]或Integer[]。就像JComboBox允许这样做一样:
String [] groups = {null, "Zombies","Instigators","Fantastic Beasts","Stranger Things"};
JComboBox<String> groupSelector = new JComboBox<String>(groups);
totalNum = new JComboBox<Integer>();
totalNum.addItem(null);
totalNum.addItem(0); totalNum.addItem(1);
totalNum.addItem(2); totalNum.addItem(3);
totalNum.addItem(4);发布于 2022-07-18 18:06:07
要传递到ComboBox类的构造函数的数组需要传递给JComboBox的构造函数。
public ComboBox(E[] items) {
super(items);
}您的代码没有抛出错误的原因是JComboBox还有另一个构造函数,它不需要任何参数(您目前正在调用构造函数https://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html#JComboBox(),但希望调用https://docs.oracle.com/javase/7/docs/api/javax/swing/JComboBox.html#JComboBox(E[])。但是,您需要调用以Array作为参数的构造函数。这就是为什么必须将参数传递给调用的超级()-methid的原因。
https://stackoverflow.com/questions/73026535
复制相似问题