package framework; import javax.swing.*; import javax.swing.event.*; import java.awt.event.*; import java.awt.*; import java.lang.reflect.*; /** Utilities for unrelated tasks. */ public class FrameworkUtils { /** * This method constructs a menu containing the specified items. * The name of each item may contain the '&' character in front of the * letter to be used as the keyboard shortcut for that item. Otherwise the * first letter will be designated as the shortcut key. * * A null item indicates a separator. * * Here's a sample call: * * JMenu fileMenu = makeMenu("&File", new String[] * {"&New", "&Save", "Sa&ve As", "&Load", "&Quit"}); * * @param name The name of the menu * @param items The list of menu items * * @return The constructed menu */ public static JMenu makeMenu(String name, String[] items, Controller handler) { JMenu result; int j = name.indexOf('&'); if ( j != -1) { char c = name.charAt(j + 1); String s = name.substring(0, j) + name.substring(j + 1); result = new JMenu(s); result.setMnemonic(c); } else { result = new JMenu(name); } MenuListener menuListener = new MenuListenerAdapter(); for(int i = 0; i < items.length; i++) { if (items[i] == null) { result.addSeparator(); } else { j = items[i].indexOf('&'); JMenuItem item; if ( j != -1) { char c = items[i].charAt(j + 1); String s = items[i].substring(0, j) + items[i].substring(j + 1); item = new JMenuItem(s, items[i].charAt(j + 1)); item.setAccelerator( KeyStroke.getKeyStroke(c, InputEvent.CTRL_MASK)); } else { // no accelerator or shortcut key item = new JMenuItem(items[i]); } item.addActionListener(handler); result.add(item); } result.addMenuListener(menuListener); } return result; } /** * A simple utility for handling errors. */ public static void error(String gripe) { JOptionPane.showMessageDialog(null, gripe, "OOPS!", JOptionPane.ERROR_MESSAGE); } /** * A simple parser for converting strings into types. */ public static Type getType(String typeName) throws AppError { Type result = null; try { return Class.forName(typeName); } catch (ClassNotFoundException e) { if (typeName.equals("int")) return Integer.TYPE; if (typeName.equals("double")) return Double.TYPE; if (typeName.equals("boolean")) return Boolean.TYPE; if (typeName.equals("void")) return Void.TYPE; if (typeName.equals("char")) return Character.TYPE; if (typeName.equals("float")) return Float.TYPE; if (typeName.equals("byte")) return Byte.TYPE; if (typeName.equals("short")) return Short.TYPE; if (typeName.equals("long")) return Long.TYPE; // more? throw new AppError("Unknown type: " + typeName); } } }