现在的位置: 首页 > 综合 > 正文

改进JPopupMenuButton增加记忆功能

2018年01月30日 ⁄ 综合 ⁄ 共 2171字 ⁄ 字号 评论关闭

在上面文章中实现了JPopupMenuButton

现在实现如下功能(改进)

思路
1 每次点击菜单的时候保存这个菜单的index,并且出发菜单下表变更事件
2 在JPopupButton中 监听事件, 并调用attachActionOnPopupMenu 绑定点击按钮所执行的菜单

实现:
JPopupMenu 达不到要求, 需要改造一下

package info.mikewang.part.test;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.util.Vector;

import javax.swing.AbstractButton;
import javax.swing.JPopupMenu;
import javax.swing.MenuElement;

class JPopupButtonMenu extends JPopupMenu {
	private static final long serialVersionUID = -8812143869773395718L;

	private int clickedMenuIndex = -1;

	public JPopupButtonMenu() {
		this(null);
	}

	public JPopupButtonMenu(String label) {
		super(label);
		addContainerListener(new XContainerListener());
	}

	public int getClickedMenuIndex() {
		return clickedMenuIndex;
	}

	public AbstractButton[] getSubClickedElements() {
		AbstractButton result[];
		Vector<AbstractButton> tmpx = new Vector<AbstractButton>();

		MenuElement tmp[] = getSubElements();
		for (MenuElement menuElement : tmp) {
			if (menuElement instanceof AbstractButton) {
				tmpx.add((AbstractButton) menuElement);
			}
		}

		result = new AbstractButton[tmpx.size()];
		for (int i = 0; i < tmpx.size(); i++) {
			result[i] = tmpx.elementAt(i);
		}

		return result;
	}

	// ----------------------------------

	class XContainerListener implements ContainerListener {

		@Override
		public void componentAdded(ContainerEvent e) {
			Component c = e.getChild();
			if (c instanceof AbstractButton) {
				((AbstractButton) c).addActionListener(new XActionListener());
			}
		}

		@Override
		public void componentRemoved(ContainerEvent e) {

		}
	}

	class XActionListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			AbstractButton ab = (AbstractButton) e.getSource();
			AbstractButton abs[] = getSubClickedElements();
			for (int i = 0; i < abs.length; i++) {
				if (ab == abs[i]) {
					int oldClickedMenuIndex = clickedMenuIndex;
					clickedMenuIndex = i;
					firePropertyChange("clickedMenuIndex", oldClickedMenuIndex, i);
					break;
				}
			}
		}
	}
}

JPopupButton 本部分都差不多, 就增加了一个属性监听器, 监听clickedMenuIndex, 并调用attachActionOnPopupMenu, 改变下标

private void initClickRemember() {
		menu.addPropertyChangeListener("clickedMenuIndex",
				new PropertyChangeListener() {
					@Override
					public void propertyChange(PropertyChangeEvent evt) {
						Integer ii = (Integer) evt.getNewValue();
						attachActionOnPopupMenu(ii.intValue());
					}
				});
	}

 

抱歉!评论已关闭.