简体   繁体   English

将组合框对象投射回其正确的类型

[英]Casting combobox objects back to their correct type

I have a combobox of objects (two types; ProductGroup and Family). 我有一个对象组合框(两种类型; ProductGroup和Family)。 I would like to use a command 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 注意:我是Java的新手,所以我可能需要进一步澄清一些答案

Your code should works fine. 您的代码应该可以正常工作。 Problem will be somewhere else. 问题将在其他地方。 Use debugger, or write "System.out.println(cbFamily.getSelectedItem().getClass());" 使用调试器,或编写“ 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? 如何实现一个返回类名的toString()函数呢? Or making use of Object.getName() . 或利用Object.getName() You can also try overriding it and make your own. 您也可以尝试覆盖它并自己制作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM