Converting a type Object to a type JButton?
Hi guys I have a problem, I have an object of type Object Class and I want to convert it to an object of type java.swing.JButton is there any ways to do that? here is the code:
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 zz开发者_运维知识库z = ob.getClass();
System.out.println(zzz);
} else {
AddEventHandlerButton.setEnabled(false);
}
}catch(Exception ex){
JOptionPane.showMessageDialog(null,
"Error",
"Inane error",
JOptionPane.ERROR_MESSAGE);
}
}
any ideas? thanks
You probably just want a cast (possibly with an instanceof
check first, as shown by Andreas; it depends on what you want to happen if the object you find isn't a JButton
):
JButton button = (JButton) ob;
but there's more detail to go into here. You should differentiate between the type of an object and the type of a variable.
In your case, the type of ob
itself is definitely Object
. However, the value of ob
may be a reference to an instance of JButton
- in which case you're okay to cast, as above.
Note that this doesn't change the type of the object at all. Once an object has been created, it will never change its type. All you're doing is declaring a new variable of type JButton
and asking the JVM to check that the value of ob
really does refer to an instance of JButton
(or a subclass; or that it's a null reference). If that's the case, the value of button
will end up being the same as the value of ob
(i.e. a reference to the same object). If it's not, a ClassCastException
will be thrown.
Do you see what I mean about the difference between the type of the variable and the type of the object it happens to refer to? It's very important to understand this difference.
Converting a Class instance to a JButton instance, aka casting, is not possible, not the right way. But you use the Class object to create a new instance of JButton:
Class<JButton> buttonClass = JButton.class;
JButton button = buttonClass.newInstance();
But it looks like you expect to get a button through findObject and want to add a listener to an already existing button, I suggest doing it like that:
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
});
精彩评论