[英]Dynamically register listeners in swing
I have created UI that populates components dynamically. 我创建了可以动态填充组件的UI。 The UI is like table, which has X number of rows, but having 4 components [1 JLable, 3 JComboboxes] in each row.
UI就像表,具有X行数,但每行中有4个组件[1 JLable,3 JComboboxes]。 I want to register listeners for all comboboxes, to fetch the selectedItem() from comboboxes and use it for further reference.
我想为所有组合框注册侦听器,以从组合框获取selectedItem()并将其用作进一步参考。 But, I am not able to do it using my existing code.
但是,我无法使用现有代码来做到这一点。 The code is below.
代码如下。
for(int i=0; i< list.size(); i++) {
final int j = i;
cb1[i] = new JCombobx();
masterPanel[i].add(cb1[i]);
cb2[i] = new JCombobx();
masterPanel[i].add(cb2[i]);
cb3[i] = new JCombobx();
masterPanel[i].add(cb3[i]);
cb1[j].addItem("Select Value");
for (OtherObject l : List) {
cb1[j].addItem(l);
}
cb1[j].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectedValue = (SomeObject) cb1[j].getSelectedItem();
}
});
}
I am getting this exception : 我收到此异常:
java.lang.ClassCastException: java.lang.String cannot be cast to SomeObject
In this, combobox[cb2] will be populated according to the value selected from cb1 and eventually third combobox will be populated according to the value selected from cb2. 在这种情况下,combobox [cb2]将根据从cb1中选择的值进行填充,最终第三个组合框将根据从cb2中选择的值进行填充。 What's wrong in it?
怎么了
The exception is very clear: obviously, you put strings into your first combo box object (in the code that you aren't showing here). 异常非常明显:显然,您将字符串放入了第一个组合框对象(在此处未显示的代码中)。
A string object can never be casted to (SomeObject) class. 字符串对象永远不能转换为(SomeObject)类。
So, there are two ways to fix that: 因此,有两种方法可以解决此问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.