Swing菜单与工具栏(五)

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所示。每一个弹出菜单将会在三秒后消失。在这个例子中,选择弹出菜单只会在控制台显示一条消息。

swing_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);
	}
 
}
原文地址:https://www.cnblogs.com/dyllove98/p/2461908.html