Java Reference
In-Depth Information
Inner Classes as Event Handlers
A common use of inner classes is for event handlers. An event handler is the type of
object that often needs access to the members of its outer class but likely won't be
reused by another class, making it a good candidate for an inner class. The
ColorChanger
class discussed in Listing 2.1 earlier in this chapter declared a member inner class named
MyButtonListener
:
7. public class ColorChanger extends Frame {
8. private Button redBtn, whiteBtn, blueBtn;
23. private class MyButtonListener implements ActionListener {
24. public void actionPerformed(ActionEvent e) {
25. String label = e.getActionCommand();
26. if(label.equals(redBtn.getLabel())) {
27. ColorChanger.this.setBackground(RED);
28. } else if(label.equals(whiteBtn.getLabel())) {
29. ColorChanger.this.setBackground(WHITE);
30. } else if(label.equals(blueBtn.getLabel())) {
31. ColorChanger.this.setBackground(BLUE);
32. }
33. }
34. }
54. private void initializeEvents() {
55. MyButtonListener m = new MyButtonListener();
56. redBtn.addActionListener(m);
57. whiteBtn.addActionListener(m);
58. blueBtn.addActionListener(m);
59. }
60. //Remainder of class definition...
71. }
Notice the
MyButtonListener
class uses the special
this
syntax for accessing the
setBackground
method that
ColorChanger
inherits from
Frame
. The inner class also
references the three private
Button
fi elds of the outer class.
Search WWH ::
Custom Search