6.2 使用彈出菜單:Popup類
並不是我們希望彈出的所有內容都需要是一個菜單。通過Popup與PopupFactory類,我們可以在其他的組件上彈出任何組件。這與工具提示不同,工具提示是隻讀的不可選擇的標簽。我們可以彈出可選擇的按鈕,樹或是表。
6.2.1 創建彈出組件
Popup是一個具有兩個方法hide()與show()的簡單類,同時具有兩個受保護的構造函數。我們並不能直接創建Popup對象,而是需要由PopupFactory類獲取。
PopupFactory factory = PopupFactory.getSharedInstance();
Popup popup = factory.getPopup(owner, contents, x, y);由PopupFactory所創建的帶有contents組件的Popup則會位於owner組件內的其他組件之上。
6.2.2 一個完整的Popup/PopupFactory使用示例
列表6-7演示瞭在另一個JButton之上顯示瞭一個JButton的Popup與PopupFactory的使用示例。選擇初始的JButton會使得在第一個JButton之上,在隨機位置創建第二個。當第二個按鈕可見時,每一個都是可選擇的。多次選擇初始的可見按鈕會出現多個彈出按鈕,如圖6-9所示。每一個彈出菜單將會在三秒後消失。在這個例子中,選擇彈出菜單隻會在控制臺顯示一條消息。
package net.ariel.ch06;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.Timer;
public class ButtonPopupSample {
static final Random random = new Random();
// define ActionListener
static class ButtonActionListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println(“Selected: “+event.getActionCommand());
}
};
// define show popu ActionListener
static class ShowPopupActionListener implements ActionListener {
private Component component;
ShowPopupActionListener(Component component) {
this.component = component;
}
public synchronized void actionPerformed(ActionEvent event) {
JButton button = new JButton(“Hello, world”);
ActionListener listener = new ButtonActionListener();
button.addActionListener(listener);
PopupFactory factory = PopupFactory.getSharedInstance();
int x = random.nextInt(200);
int y = random.nextInt(200);
final Popup popup = factory.getPopup(component, button, x, y);
popup.show();
ActionListener hider = new ActionListener() {
public void actionPerformed(ActionEvent event) {
popup.hide();
}
};
// hide popup in 3 seconds
Timer timer = new Timer(3000, hider);
timer.start();
}
};
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Runnable runner = new Runnable() {
public void run() {
// create frame
JFrame frame = new JFrame(“Button Popup Sample”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ActionListener actionListener = new ShowPopupActionListener(frame);
JButton start = new JButton(“Pick Me for Popup”);
start.addActionListener(actionListener);
frame.add(start);
frame.setSize(350, 250);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}