直接看程序:import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Test{
public static void main(String args[]){
MyFrame myFrame = new MyFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
class MyFrame extends JFrame{
public MyFrame(){
setTitle("MyFrame");
setLocation(400,300);
setSize(450,300);
MyPanel myPanel = new MyPanel();
getContentPane().add(myPanel);
}
}
class MyPanel extends JPanel{
public MyPanel(){
ColorAction yellowAction = new ColorAction("Yellow",Color.YELLOW);
ColorAction blueAction = new ColorAction("Blue",Color.BLUE);
JButton button1 = new JButton(yellowAction);
JButton button2 = new JButton(blueAction);
add(button1);
add(button2);
InputMap mi = getInputMap(JComponent.WHEN_FOCUSED);   //   ...A
  //InputMap mi = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);  // ...B
mi.put(KeyStroke.getKeyStroke("ctrl A"),"to-Yellow");
mi.put(KeyStroke.getKeyStroke("ctrl B"),"to-Blue");
ActionMap ma = getActionMap();
ma.put("to-Yellow",yellowAction);
ma.put("to-Blue",blueAction);
}
    class ColorAction extends AbstractAction{
public ColorAction(String name,Color c){
putValue(Action.NAME,name);
putValue("Color",c);
}
    public void actionPerformed(ActionEvent e){
     Color c = (Color)getValue("Color");
     setBackground(c);
    }
}
}
//注释处,为什么写A或者写B都是同样的效果?