Java Reference
In-Depth Information
This is a cheap operation requiring only six lines. Recompile, create a few elements, and then watch
them disappear with a right button click.
How It Works
After verifying that highlightElement is not null , we call the remove() method that we added in
the SketchModel class way back. This will delete the element from the list, so when the view is
repainted it will no longer be displayed. The repaint occurs automatically because the update()
method for the view - the method we implemented for the Observer interface - will be called because
the model has changed. Of course, we must remember to set highlightElement to null too,
otherwise it could get drawn by a mouse handler even though it is no longer in the model.
Let's do another easy one - Send-to-Back.
Implementing the Send-to-Back Operation
The send-to-back operation is really an extension of the delete operation. We can move an element
from wherever it is in the list by deleting it, then adding it again at the end of the list.
Try It Out - The Send-to-Back Operation
The actionPerformed() method in the SketchView class has the job of removing the highlighted
element from wherever it is in the model, and then adding it back at the end:
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == moveItem) {
// (Process a move...)
} else if(source == deleteItem) {
// Code as inserted here earlier
} else if(source == rotateItem) {
// (Process a rotate)
} else if(source == sendToBackItem) {
if(highlightElement != null) {
theApp.getModel().remove(highlightElement);
theApp.getModel().add(highlightElement);
highlightElement.setHighlighted(false);
highlightElement = null;
repaint();
}
}
}
A little harder this time - eight lines of code. You can try this by drawing a few concentric circles, with
the outermost drawn first. An outer circle will prevent an inner circle from being highlighted, but
applying Send-to-back to the outer circle will make the inner circle accessible.
Search WWH ::




Custom Search