新手求教 [ java教程]
按照JAVA核心技术8.2动作一节写了段代码,想起到点击按钮改变窗口颜色,同时键盘也可以控制按钮的效果,结果运行的时候按钮点击可以改变颜色,但是按键盘没有反应,自己整了半天没搞明白,求各位大神帮助。代码如下:
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class ActionFrame extends JFrame{
public static void main(String[] args)
{
JFrame J=new ActionFrame();
J.setTitle("ActionFrame");
J.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
J.setVisible(true);
J.setSize(300, 300);
}
JPanel B=new JPanel();
public ActionFrame() {
add(B);
Action YellowAction=new ColorAction("Yellow",Color.YELLOW);
Action BlueAction=new ColorAction("Blue",Color.BLUE);
Action RedAction=new ColorAction("Red",Color.RED);
B.add(new JButton(YellowAction));
B.add(new JButton(BlueAction));
B.add(new JButton(RedAction));
InputMap imap=B.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
imap.put(KeyStroke.getKeyStroke("Y")," yellow");
imap.put(KeyStroke.getKeyStroke("B")," blue");
imap.put(KeyStroke.getKeyStroke("R")," red");
ActionMap amap=B.getActionMap();
amap.put("yellow",YellowAction);
amap.put("blue",BlueAction);
amap.put("red",RedAction);
}
public class ColorAction extends AbstractAction
{
public ColorAction(String name,Color c)
{
putValue(Action.NAME,name);
putValue(Action.SHORT_DESCRIPTION,"set color to"+name.toLowerCase());
putValue("color",c);
}
public void actionPerformed(ActionEvent e) {
Color c=(Color)getValue("color");
B.setBackground(c);
}
}
}