Java Reference
In-Depth Information
Working with Pop-Ups: The Popup Class
Not everything you want to pop up needs to be a menu. Through the Popup and PopupFactory
classes, you can pop up any component over another. This is different from tooltips, which are
in a read-only, unselectable label. You can pop up selectable buttons, trees, or tables.
Creating Pop-Up Components
Popup is a simple class with two methods— hide() and show() —with two protected construc-
tors. Instead of creating Popup objects directly, you acquire them from the PopupFactory class.
PopupFactory factory = PopupFactory.getSharedInstance();
Popup popup = factory.getPopup(owner, contents, x, y);
The Popup with the contents component created by PopupFactory will thus be “above”
other components within the owner component.
A Complete Popup/PopupFactory Usage Example
Listing 6-7 demonstrates the usage of Popup and PopupFactory to show a JButton above another
JButton . Selecting the initial JButton will cause the second one to be created above the first, at
some random location. When the second button is visible, each is selectable. Selecting the initially
visible button multiple times will cause even more pop-up buttons to appear, as shown in
Figure 6-9. Each pop-up button will disappear after three seconds. In this example, selecting
the pop-up button just displays a message to the console.
Figure 6-9. Popup/PopupFactory example
Listing 6-7. The ButtonPopupSample Class Definition
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class ButtonPopupSample {
 
Search WWH ::




Custom Search