view src/samer/core_/util/swing/MenuBuilder.java @ 8:5e3cbbf173aa tip

Reorganise some more
author samer
date Fri, 05 Apr 2019 22:41:58 +0100
parents bf79fb79ee13
children
line wrap: on
line source
/*
 *	MenuBuilder.java	
 *
 *	Copyright (c) 2000, Samer Abdallah, King's College London.
 *	All rights reserved.
 *
 *	This software is provided AS iS and WITHOUT ANY WARRANTY; 
 *	without even the implied warranty of MERCHANTABILITY or 
 *	FITNESS FOR A PARTICULAR PURPOSE.
 */

package samer.core.util.swing;
import  samer.core.util.*;
import  samer.core.*;
import  javax.swing.*;
import  java.awt.*;
import  java.awt.event.*;

public class MenuBuilder implements Agent.Registry 
{
	JPopupMenu		menu;
	AgentAdapter	ad;

	public MenuBuilder(JPopupMenu m, AgentAdapter a) { menu=m; ad=a; }

	public Agent.Registry add(String l) 
	{ 
		// could get icon here
		JMenuItem mi = new JMenuItem(l);
		mi.addActionListener(ad);
		menu.add(mi);
		return this;
	}
	public Agent.Registry add(String l, boolean state) 
	{
		// could get icon here
		JCheckBoxMenuItem mi = new JCheckBoxMenuItem(l, state);
		mi.setName(l);
		mi.addItemListener(ad);
		menu.add(mi);
		return this;
	}
	public void group() { menu.addSeparator(); }

	public void setTarget(Agent a) { ad=new AgentAdapter(a); group(); }

	public static PopupHandler addPopup(JPopupMenu popup, Component c) {
		PopupHandler h=new PopupHandler(popup); 
		insertML(h,c); return h;
	}
	
	private static void insertML(MouseListener l, Component c) {
		// what if this listener isn't there?
		c.removeMouseListener(MouseRetarget.listener);
		c.addMouseListener(l);
		c.addMouseListener(MouseRetarget.listener);
	}

	/** Add commands for given Agent to given menu, to be show in given component.
		If menu is null, then a new menu is created and associated with the component
		using a popup menu mouse handler. The popup will be shown when the user
		right clicks in the component.
	*/
	
	public static JPopupMenu showCommands( Agent agent, Component c, JPopupMenu menu)
	{
		if (menu==null) {
			menu=new JPopupMenu(c.getName());
			addPopup(menu, c);
		} else {
			menu.addSeparator();
		}

		agent.getCommands( new MenuBuilder(menu,new AgentAdapter(agent)));
		return menu;
	}

	/** Add commands for given Agent to the given DynamicPopupHandler. This maintains
		a list of agents, so when the handler is triggered by the user right-clicking in
		the given component, a popup menu is built dynamically from the commands reported
		by the Agents.
		*/

	public static DynamicPopupHandler showCommands( Agent agent, Component c, DynamicPopupHandler h)
	{
		if (h==null) {
			h=new DynamicPopupHandler(c.getName());
			insertML(h,c);
		}
		h.addAgent(agent);
		return h;
	}
};