Java Reference
In-Depth Information
By necessity, AppletMenuBar is an AWT component. Developing custom Swing
components is similar, but there are a few key differences. For instance, Swing
components draw themselves in the paintComponent() method, not the paint()
method. If you want your custom Swing component to support pluggable look-
and-feels, you have to define a javax.swing.plaf.ComponentUI for it. You can
read more about custom Swing components at the end of Chapter 4 of Java Foun-
dation Classes in a Nutshell . Finally, although you can use AppletMenuBar in Swing
GUIs, you should not. First, there is no need. Second, its look-and-feel does not
match that of other Swing components. And third, mixing “heavyweight” compo-
nents such as this one with “lightweight” Swing components can cause layout and
redisplay problems.
Example 10•29: AppletMenuBar.java
package com.davidflanagan.examples.gui;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
public class AppletMenuBar extends Panel {
// Menubar contents
Vector labels = new Vector();
Vector menus = new Vector();
// Properties
Insets margins = new Insets(3, 10, 3, 10); // top, left, bottom, right
int spacing = 10;
// Space between menu labels
Color highlightColor;
// Rollover color for labels
// internal stuff
boolean remeasure = true; // Whether the labels need to be remeasured
int[] widths; // The width of each label
int[] startPositions; // Where each label starts
int ascent, descent; // Font metrics
Dimension prefsize = new Dimension(); // How big do we want to be?
int highlightedItem = -1;
// Which item is the mouse over?
/**
* Create a new component that simulates a menubar by displaying
* the specified labels. Whenever the user clicks the specified label,
* popup up the PopupMenu specified in the menus array.
* Elements of the menus arra may be a static PopupMenu object, or
* a PopupMenuFactory object for dynamically creating menus.
* Perhaps we'll also provide some other kind of constructor or factory
* method that reads popup menus out of a config file.
*/
public AppletMenuBar() {
// We'd like these kinds of events to be delivered
enableEvents(AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
/** Add a popup menu to the menubar */
public void addMenu(String label, PopupMenu menu) {
insertMenu(label, menu, -1);
}
/** Insert a popup menu into the menubar */
Search WWH ::




Custom Search