Keys.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
Demonstration of simple KeyStroke mapping.
*/
class Keys extends JFrame
{
public static void main(String argv[])
{
Keys f = new Keys();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.show();
}
public Keys()
{
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension ss = kit.getScreenSize();
setSize(ss.width/3,2*ss.height/4);
setLocation(ss.width/4,ss.height/4);
setTitle("CISC370-011 -- KeyStroke mapping");
JPanel sp = new JPanel();
Container contentPane = getContentPane();
contentPane.add(sp);
// Create a File menu.
JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar);
JMenu fileMenu = new JMenu("File");
mbar.add(fileMenu);
// Create a Color submenu.
JMenu optionsMenu = new JMenu("Colors");
fileMenu.addSeparator();
fileMenu.add(optionsMenu);
// Create a list of colors and names.
class Bozo {
Color c;
String name;
char key;
Bozo(Color c,String name,char key)
{ this.c = c; this.name = name; this.key = key; }
}
Bozo[] clist = {
new Bozo(Color.WHITE,"White",'W'),
new Bozo(Color.RED,"Red",'R'),
new Bozo(Color.ORANGE,"Orange",'O'),
new Bozo(Color.YELLOW,"Yellow",'Y'),
new Bozo(Color.GREEN,"Green",'G'),
new Bozo(Color.BLUE,"Blue",'B'),
new Bozo(Color.PINK,"Pink",'P'),
new Bozo(Color.MAGENTA,"Magenta",'M'),
};
// Create an Action object for each color, add the Action
// to buttons and menus, and map its keystroke.
for (int i=0; i<clist.length; i++) {
ColorAction action =
new ColorAction(sp,clist[i].c,clist[i].name);
JButton button = new JButton(action);
sp.add(button);
JMenuItem option = new JMenuItem(action);
optionsMenu.add(option);
// Map both upper- and lower-case versions of this
// keystroke to the panel (to catch the keystrokes
// no matter what component has the focus).
ActionMap amap = sp.getActionMap();
InputMap imap = sp.getInputMap(
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
char key = clist[i].key;
KeyStroke ks1 =
KeyStroke.getKeyStroke(Character.toUpperCase(key));
KeyStroke ks2 =
KeyStroke.getKeyStroke(Character.toLowerCase(key));
String aname = "color."+clist[i].name; // Name for action.
imap.put(ks1,aname);
imap.put(ks2,aname);
amap.put(aname,action);
}
// Finally, add an Exit item to the File menu.
JMenuItem exitItem = new JMenuItem("Exit");
fileMenu.add(exitItem);
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{ System.exit(0); }
});
}
}
/**
This class represents an <code>Action</code> that, whenever triggered,
sets the background of a given JPanel to a specified color.
*/
class ColorAction extends AbstractAction
{
public ColorAction(JPanel p,Color c,String name)
{
super(name);
this.color = c;
this.panel = p;
}
public void actionPerformed(ActionEvent e)
{
panel.setBackground(color);
}
private JPanel panel;
private Color color;
}