package chapter08;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.Icon;
import javax.swing.ImageIcon;
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 ActionFrameAncestor {
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
ActionFrame actionFrame=new ActionFrame();
actionFrame.setTitle("输入-动作映射");
actionFrame.setVisible(true);
actionFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
}
class ActionFrame extends JFrame{
private JPanel buttonPanel;
private static final int DEFAULT_WIDTH=400;
private static final int DEFAULT_HEIGHT=300;
public ActionFrame(){
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
buttonPanel=new JPanel();
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Action redAction=new ColorAction("Red",new ImageIcon("red-ball.gif"),Color.RED);
Action blueAction=new ColorAction("Blue",new ImageIcon("bule-ball.gif"),Color.BLUE);
Action yellowAction=new ColorAction("Yellow",new ImageIcon("yellow-ball.gif"),Color.YELLOW);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
buttonPanel.add(new JButton(redAction));
buttonPanel.add(new JButton(blueAction));
buttonPanel.add(new JButton(yellowAction));
add(buttonPanel);
InputMap imap=buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
imap.put(KeyStroke.getKeyStroke("ctrl Y"),"panel.yellow");
imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");
ActionMap amap=buttonPanel.getActionMap();
amap.put("panel.yellow", yellowAction);
amap.put("panel.blue", blueAction);
amap.put("panel.red", redAction);
}
private class ColorAction extends AbstractAction{
public ColorAction(String name,Icon icon,Color c){
putValue(Action.NAME,name);
putValue(Action.SMALL_ICON,icon);
putValue(Action.SHORT_DESCRIPTION,"set panel color to"+name.toLowerCase());
putValue("Color",c);
}
public void actionPerformed(ActionEvent event){
buttonPanel.setBackground((Color)getValue("Color"));
}
}
}
大神们,看看那标记的三行,运行的结果和书上的不一样,我的是
书上点点点处是红色,蓝色,黄色的三个点!
请教大家应该怎么搞?
------解决方案--------------------
没看太懂你代码,不过你38到42那几行,new ImageIcon()明细引用的是red-ball.gif这种的图片,所以你这个三个图片的路径是不是没写对,所以没有引用到。
------解决方案--------------------
不是的,空指针是你调用没有实例化的对象或对象为空时的方法或属性,如 user.getName();如果user为空,就会报空指针;
你这个获取不到资源,就不会显示这个图标啊。
验证上面猜测很简单,你把red-ball.gif绝对路径写上,如c://images/red-ball.gif 这样试一下,如果可以显示,就说明确实是路径不正确。然后再优化程序,方便程序移植不要使用绝对路径。