0

大家好,我有一个问题,我有一个 Object Class 类型的对象,我想将它转换为 java.swing.JButton 类型的对象,有什么方法可以做到这一点吗?这是代码:

private void EventSelectedFromList(java.awt.event.ActionEvent evt) {                                       
        // add code here
        try
        {
            String eventName = (String)EventList.getSelectedItem();// get the event 
            EventSetDescriptor ed = eventValue(events,eventName);
            if(ed.getListenerType() == ActionListener.class){// check if selected event has an actionListerner listener
                AddEventHandlerButton.setEnabled(true);// Enable eventhandler button
                String objectName = (String) ObjectList.getSelectedItem();
                Object ob = FindObject(hm, objectName);// retrieve the object from hashmap
                // now 'ob' of type of JButton, I want to add ActionListener to this JButton???

                Class zzz = ob.getClass();
                System.out.println(zzz);

            } else {
                AddEventHandlerButton.setEnabled(false);
            }
        }catch(Exception ex){
                JOptionPane.showMessageDialog(null,
                "Error",
                "Inane error",
                JOptionPane.ERROR_MESSAGE);
        }

    }                   

有任何想法吗?谢谢

4

2 回答 2

5

可能只想要一个演员表(可能instanceof首先进行检查,如 Andreas 所示;如果您找到的对象不是 a ,这取决于您想要发生的事情JButton):

JButton button = (JButton) ob;

但这里还有更多细节需要介绍。您应该区分对象的类型和变量的类型。

在你的情况下,ob它本身的类型肯定是Object. 但是, 的值ob可能是对JButton- 实例的引用,在这种情况下,您可以像上面那样进行强制转换。

请注意,这根本不会改变对象的类型。一旦创建了一个对象,它就永远不会改变它的类型。您所做的只是声明一个新的类型变量JButton并要求 JVM 检查 的值是否确实ob引用了(或子类;或者它是空引用)的实例。如果是这种情况,则 的值最终将与 的值相同(即对同一对象的引用)。如果不是,a将被抛出。JButtonbuttonobClassCastException

你明白我所说的变量类型和它碰巧引用的对象类型之间的区别是什么意思吗?了解这种差异非常重要。

于 2010-09-02T06:10:21.440 回答
2

将 Class 实例转换为 JButton 实例(也称为强制转换)是不可能的,这不是正确的方法。但是您使用 Class 对象来创建 JButton 的实例:

 Class<JButton> buttonClass = JButton.class;
 JButton button = buttonClass.newInstance();

但看起来您希望通过 findObject 获得一个按钮,并希望将一个侦听器添加到一个已经存在的按钮,我建议这样做:

Object ob = findObject(hm, objectName);
if (!(ob instanceof JButton)) {
   // handle error and return/throw exception
}
JButton button = (JButton) ob;
button.addActionListener(new ActionListener(){ 
   // implement methods
});
于 2010-09-02T06:12:10.343 回答