我面临设置自定义JComboBox的相关值的问题。如果我从下面类的initialize()
方法调用setSelectedItem()
,它不是在选择特定的值。
扩展的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;
}*/
}
我无法理解我做错了什么。任何信息对我都很有帮助。
提前谢谢。
1)我希望主方法是从invokeLater
初始化的
2) Swing是单线程的,向GUI的输出很快就完成了
3) 不能保证所有事件都有任何顺序,基本上不可能为Swing GUI排序事件,同样/特别是在GUI启动时
4) 显示GUI(setVisible(true);
),则最后一个代码行将是JComboBox#setSelectedItem(int or Object)
,封装在invokeLater
中
5) 仅在需要时添加Listeners
,删除无用的Listeners