Java Reference
In-Depth Information
frame.add(toolbar, BorderLayout.NORTH);
frame.add(drawingPanel, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
The UndoableDrawingPanel class is a component that draws a polygon within itself based
on a set of points within the polygon. New points are added to the polygon whenever the
mouse is released. If you don't want the component to support undoable operations, you don't
need to do anything beyond collecting points for the drawing panel.
For the panel to support undoable operations, it must do two things:
It must maintain a list of UndoableEditListener objects. This can be easily done with the
help of the UndoableEditSupport class, as shown earlier in Listing 21-3.
The second task involves creating an UndoableEdit object, prior to any state changes,
and posting it to the registered listeners. Because the state of the drawing panel is the
polygon, this property must be exposed in the drawing class.
Listing 21-5 shows the definition for the UndoableDrawingPanel class. Nothing in the class
is particularly complicated. The important thing to remember when defining an undoable
class is that the undoable event must be created before the state of the component changes.
(The implementation class of the UndoableEdit interface, UndoableDrawEdit , is shown later,
in Listing 21-6.)
Listing 21-5. The UndoableDrawingPanel Main Component
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.undo.*;
import java.awt.*;
import java.awt.event.*;
public class UndoableDrawingPanel extends JPanel {
UndoableEditSupport undoableEditSupport = new UndoableEditSupport(this);
Polygon polygon = new Polygon();
Search WWH ::




Custom Search