java 动作与键盘事件的对应 ActionEvent InputMap KeyStroke

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

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;

/*
 * 3个按钮一个面板
 * 点击不同按钮 面板呈现不同颜色
 * 增加功能:按键盘ctrl+y    alt+g    r面板也会变色
 * 
 * 动作与键盘事件的对应
 */
public class ActionEventDemo2 extends JFrame{

JPanel ChangeColorPanel;

public ActionEventDemo2() {
JPanel buttonPanel = new JPanel();//放button的面板
ChangeColorPanel =new JPanel();//此面板颜色会变
/*创建Action对象*/
Action yelloChane=new PanelColorChange("yellowButton", Color.YELLOW);
Action redChane = new PanelColorChange("redButton", Color.RED);
Action greenChane = new PanelColorChange("greenButton", Color.GREEN);
GridLayout gridLayout=new GridLayout(1, 3);
buttonPanel.setLayout(gridLayout);
buttonPanel.add(new JButton(yelloChane));//yelloChane是AbstractAction子类对象 相当于注册了ActionEvent事件
buttonPanel.add(new JButton(redChane));//将事件当做参数再定义组件时就传递过去 省了addXXXListener和继承XXXListenner的过程
buttonPanel.add(new JButton(greenChane));

//动作与键盘事件相对应
//键盘与对象建立联系
InputMap inputMap=buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inputMap.put(KeyStroke.getKeyStroke("ctrl Y"), "yello");//组合件ctrl+Y Y一定要大写ctrl的c一定要小写
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_G,InputEvent.ALT_MASK), "green");//组合键alt+g
inputMap.put(KeyStroke.getKeyStroke('r'), "red");
//动作与对象建立联系
ActionMap actionMap=buttonPanel.getActionMap();
actionMap.put("yello", yelloChane);
actionMap.put("red", redChane);
actionMap.put("green", greenChane);
//联系建立结束 最终效果=》键盘与动作建立了联系
/*
* 上面代码 inputMap利用getKeyStroke('y')将键盘y与对象"yello"对应   
* actionMap又将对象"yello"与动作yelloChane对应 
* 从而键盘'y'就与动作yelloChane对应了
* 其余同理
*/


add(buttonPanel);
BorderLayout borderLayout=new BorderLayout();
add(buttonPanel,BorderLayout.NORTH);
add(ChangeColorPanel,borderLayout.CENTER);

}


public static void main(String[] args) {
ActionEventDemo2 aed=new ActionEventDemo2();
aed.setSize(500, 300);
aed.setResizable(false);
aed.setLocationRelativeTo(null);
aed.setVisible(true);
aed.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

class PanelColorChange extends AbstractAction{
private String name="";//表示按钮名称的变量
private Color color=null;//表示颜色变化的变量
/*构造方法*/
public PanelColorChange(String name, Color color) {
super();
this.name = name;
this.color = color;
//这就是事件监听器  putValue产生鼠标放上去会有提示文本的事件
putValue(Action.NAME, name);
putValue(Action.SHORT_DESCRIPTION, "单击该按钮颜色将变为"+color);

}

@Override
public void actionPerformed(ActionEvent e) {
ChangeColorPanel.setBackground(color);//设置面板颜色为color color由构造函数传递进来
}

}

}

猜你喜欢

转载自blog.csdn.net/hza419763578/article/details/80682072
今日推荐