开发者

Casting combobox objects back to their correct type

I have a combobox of objects (two types; ProductGroup and Family). I would like to use a comman开发者_运维百科d to find out what type of object the selected item is.

I went out on a limb and tried

if (cbFamily.getSelectedItem() instanceof ProductGroup) {
    JOptionPane.showMessageDialog(mainWindow, "You have selected a ProductGroup")
}

I had no luck

Note: I am new to Java so I may need to ask for further clarification on some answers


Your code should works fine. Problem will be somewhere else. Use debugger, or write "System.out.println(cbFamily.getSelectedItem().getClass());" before your "if" to determine what class is returned from your combobox.


What about implementing a toString() function which returns the class name? Or making use of Object.getName(). You can also try overriding it and make your own.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜