在 Swing 中绑定组合框
我正在使用 Eclipse IDE 开发桌面(swing)应用程序。我有三个组合框(国家、州和城市),当我选择新的国家或省份时,我需要自动更新数据。我搜索了很多信息,但我找到的所有实现都是在Ajax或NetBeans中的bean绑定框架上实现的。 我尝试了 ItemEvent 的解决方案,但启动应用程序时遇到问题,它加载国家/地区列表,但不加载其他列表。通过选择国家,系统会显示州列表,但不会显示城市列表。
我的代码:
jComboBoxCountries.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBoxStates.setModel(new javax.swing.DefaultComboBoxModel(
statesOf(evt.getItem()).toArray() ));
}
});
jComboBoxStates.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBoxCities.setModel(new javax.swing.DefaultComboBoxModel(
citiesOf(evt.getItem()).toArray()) );
}
});
jComboBoxCountries.setModel(new javax.swing.DefaultComboBoxModel(
countryList.toArray()));
I'm working on a desktop (swing) application with Eclipse IDE. I have three comboboxes (countries, states and cities) and I need to update the data automatically when I selecting a new country or province. I searched lot of information, but all the implementations I found are made on Ajax or the beansbinding framework in NetBeans.
I tried a solution by ItemEvent, but I have problems starting my application it loads the list of countries but not the other lists. And by selecting a country is charged the list of states but not the list of cities.
My code:
jComboBoxCountries.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBoxStates.setModel(new javax.swing.DefaultComboBoxModel(
statesOf(evt.getItem()).toArray() ));
}
});
jComboBoxStates.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBoxCities.setModel(new javax.swing.DefaultComboBoxModel(
citiesOf(evt.getItem()).toArray()) );
}
});
jComboBoxCountries.setModel(new javax.swing.DefaultComboBoxModel(
countryList.toArray()));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
似乎您必须专门设置选定的索引才能调用侦听器。
我猜这是同样的问题,一旦您重置状态组合框的模型,您还需要选择其索引。
另一种方法是不选择默认的州或城市,而是提示用户选择一个。下面是一些使用这种方法的代码:
It seems like you have to specifically set the selected index to invoke the listener.
I would guess this is the same problem, once you reset the model of the states combobox you would need to select its index as well.
Another approach is to not select a default state or city, but instead prompt the user to select one. Here is some code that uses this approach: