, now aButton has a listener with a reference // to bigOne! aButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { System.out.println("Hello There"); } } In this example, serializing
aButton
by itself will cause
MyApp
and everything it refers to to be serialized as well. The problem is that the listener is serializable by coincidence, not by design. To separate the decisions about
MyApp
and the
ActionListener
being serializable one can use a nested class, as in the following example:
import java.awt.*; import java.awt.event.*; import java.io.Serializable; class MyApp java.io.Serializable { BigObjectThatShouldNotBeSerializedWithAButton bigOne; Button aButton = new Button(); static class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Hello There"); } } MyApp() { aButton.addActionListener(new MyActionListener()); } }
Note: For more information on the paint mechanisms utilitized by AWT and Swing, including information on how to write the most efficient painting code, see Painting in AWT and Swing.
For details on the focus subsystem, see How to Use the Focus Subsystem, a section in The Java Tutorial, and the Focus Specification for more information.
@version 1.451, 07/29/09
@author Arthur van Hoff
@author Sami Shaio