【发布时间】:2018-10-22 13:48:21
【问题描述】:
我的 Swing 应用程序中有 2 个组合框 - 在下面的代码中,您将看到 Spring 的元素,因为我也在使用 Spring。我不能删除 spring,否则如果没有大量重构工作来代替 Spring,应用程序就会停止工作,所以请不要问这个问题。在应用程序默认启动时,进入带有组合框的对话框时,它们应该不显示任何选择,如果您单击框打开以显示选项,则只有一个选项(“添加...”)。
问题在于,单击“添加...”后,选项关闭,但选择永远不会被替换。我想也许我需要添加一个 ActionListener 但 ActionListener(它只显示一个带有选择的消息选项窗格)似乎没有做任何事情 - 没有显示消息框。我最初开始自定义实现自己的 ComboBoxModel,但随后将其更改为从 DefaultComboBoxModel 扩展并覆盖需要不同的方法,例如 getElementAt 和 getSize 等。尽管在我的原始模型中 getSelectionItem 工作得很好(扩展默认组合框模型,我已经删除了 get 并将选择项设置为默认类为我处理了这个问题,或者我认为)。
我可能做错了什么或遗漏了什么?代码如下:
@Component
public class WordInstancePartOfSpeechComboBoxModel extends DefaultComboBoxModel<PartOfSpeech> implements Serializable
{
private static final long serialVersionUID = 2509351721137099113L;
private static final Logger msObjLogger = LoggerFactory.getLogger(WordInstancePartOfSpeechComboBoxModel.class);
private List<PartOfSpeech> mLstModel;
@Autowired
private WordInstancePartOfSpeechDialogController mObjDialogController;
protected WordInstancePartOfSpeechDialogController getDialogController()
{
return(mObjDialogController);
}
public PartOfSpeech getElementAt(final int iIndex)
{
if(iIndex > 0)
return(getModel().get(iIndex - 1));
else if(iIndex == 0)
return(new PartOfSpeech("Add..."));
else
return(null);
}
protected List<PartOfSpeech> getModel()
{
try
{
if(mLstModel == null)
mLstModel = getDialogController().listPartOfSpeeches();
}
catch(SQLException objException)
{
msObjLogger.error("Error retrieving list of Parts of Speech...", objException);
mLstModel = new ArrayList<PartOfSpeech>();
}
return(mLstModel);
}
public int getSize()
{
return(getModel().size() + 1);
}
}
以及我的 Spring 配置类中实现 JComboBox 的代码:
if(mCboWordInstancePartOfSpeech == null)
{
mCboWordInstancePartOfSpeech = new JComboBox<PartOfSpeech>(getWordInstancePartOfSpeechComboBoxModel());
mCboWordInstancePartOfSpeech.setBorder(BorderFactory.createLoweredBevelBorder());
mCboWordInstancePartOfSpeech.setFont(getDefaultFont());
mCboWordInstancePartOfSpeech.addActionListener(new ActionListener()
{
public void actionPerformed(final ActionEvent objActionEvent)
{
JComboBox<PartOfSpeech> cbo = ((JComboBox<PartOfSpeech>)(objActionEvent.getSource()));
JOptionPane.showMessageDialog(null, "The selected item is" + cbo.getSelectedIndex(), "Success!", JOptionPane.INFORMATION_MESSAGE);
}
});
}
return(mCboWordInstancePartOfSpeech);
【问题讨论】: