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

おそらく、キャストが必要なだけです(Andreasinstanceofが示すように、最初にチェックする可能性があります。見つかったオブジェクトが ではない場合に何をしたいかによって異なりますJButton):

JButton button = (JButton) ob;

しかし、ここにはさらに詳細な説明があります。オブジェクトの型と変数の型を区別する必要があります。

あなたの場合、obそれ自体のタイプは間違いなくObjectです。ただし、 の値はobのインスタンスへの参照である可能性がありますJButton- その場合、上記のようにキャストしても問題ありません。

これはオブジェクトのタイプをまったく変更しないことに注意してください。オブジェクトが作成されると、その型が変更されることはありません。行っていることは、タイプの新しい変数を宣言しJButton、JVM に値が実際にインスタンス (またはサブクラス、または null 参照) を参照していることを確認するように要求すること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 に答える