我在设置自定义JComboBox的perticulat值时遇到问题。如果我从以下类的setSelectedItem()
方法中调用initialize()
,则不会选择特定值。
扩展的JComboBox类是:
public class ThemeComboBox extends JComboBox {
private static final long serialVersionUID = 50L;
public ThemeComboBox(DefaultComboBoxModel model) {
super(model);
initialize();
LibraryLogger.initMessage(getClass().getSimpleName());
}
public void initialize() {
ThemeComboBoxModel model = (ThemeComboBoxModel) getModel();
for(ThemeModel themeModel : model.getThemeModels()) {
if(themeModel.getThemeClass().equals(ConfigurationManager.getInstance().getUiManager().getUiProperties().getTheme())) {
setSelectedItem(themeModel);
System.out.println("=========");
break;
}
}
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
ThemeComboBox themeComboBox = (ThemeComboBox) actionEvent.getSource();
System.out.println(themeComboBox.getSelectedItem());
}
});
}
}
如果我覆盖自定义DefaultComboBoxModel的getSelectedItem()
,那么它正在选择该值,但在选择其他值时,选择保持不变或保持不变。
模型类是:
public class ThemeComboBoxModel extends DefaultComboBoxModel {
private static final long serialVersionUID = 51L;
private Vector<ThemeModel> themeModels;
public ThemeComboBoxModel(Vector<ThemeModel> models) {
super(models);
}
public Vector<ThemeModel> getThemeModels() {
return themeModels;
}
public void setThemeModels(Vector<ThemeModel> themeModels) {
this.themeModels = themeModels;
}
/*@Override
public Object getSelectedItem() {
for(ThemeModel themeModel : themeModels) {
if(themeModel.getThemeClass().equals(ConfigurationManager.getInstance().getUiManager().getUiProperties().getTheme())) {
return themeModel;
}
}
return null;
}*/
}
我无法理解我做错了什么。任何信息都对我很有帮助。
提前致谢。
答案 0 :(得分:2)
1)我希望从invokeLater
2)Swing是单线程的,其中输出到GUI的时间非常短暂
3)没有任何保证所有事件都有任何订单,基本上不可能为Swing GUI订购事件,同样/特别是在GUI启动时
4)显示GUI(setVisible(true);
),然后最后一个代码行将JComboBox#setSelectedItem(int or Object)
,包含在invokeLater
5)仅在需要时添加Listeners
,删除无用的Listeners