In the java code:
// Define ActionListener
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
JButton button = **(JButton)actionEvent.getSource();**
int red = random.nextInt(255);
int green = random.nextInt(255);
int blue = random.nextInt(255);
button.setBackground(new Color(red, green, blue));
}
};
What does the highlighted (between **
and **
) code do?
I find it extremely hard to research on the subject as I do not know what sear开发者_如何学Pythonch terms to use. :o
Hope anyone can help. TIA
It's casting the object returned by actionEvent.getSource()
to a JButton
.
You can read up on some information over here and here.
It gets the source of your action which it assumes to be a JButton and casts the source of your action event to the JButton class.
The ActionEvent object represents a user action. According to your code, this action has been performed on a JButton. This object has a getSource() method that sends back the object that originated the event. However, since anything can send such events, getSource() sends back an untyped Object. You need to cast it back to its original type (Jbutton) to be able to use this source (in this cas set its background).
Check http://download.oracle.com/javase/1.4.2/docs/api/java/util/EventObject.html#getSource()
The interesting thing is the (JButton)
which is called a cast. You can use casts if you are absolutely sure that an Object of class A (called "foo" in the following) you've been given is indeed an instance of class B, then you can just write
B bar = (B) foo;
and then use the bar variable as you like. But be aware that if foo is not really an instance of B, the runtime will throw a ClassCastException
. You might also be interested in reading up on the instanceof keyword.
It's called class "casting". actionEvent.getSource() can return anything not only a JButton but also other widgets. So they decided "lets return Object because everything fits in there, and let the developer tell java what he expects" by preceeding it with (JButton) you are saying "I'm sure the source of the action event is a JButton and i want to acces it like a JButton"
精彩评论