14. 5. 2. 按钮事件及快捷键 Creating a JButton from an Action object

 

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class ContructMenuWithAction {
	public static void main(String[] args) {
		JFrame frame = new JFrame("MenuSample Example");
	    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    //这里调用了ShowAction的构造方法,把frame这个组件传来
	    JButton button = new JButton(new ShowAction(frame));
	    
	    frame.add(button);
	    frame.setSize(350, 250);
	    frame.setVisible(true);
	}
}

//AbstractAction用默认描述字符串和默认图标定义一个 Action 对象。
class ShowAction extends AbstractAction{
	Component parentComponent;
	
	public ShowAction(Component parentComponent){
		super("关于");
		/**
		 * putValue设置与指定键关联的 Value。 
		 * 参数:
		 * key - 标识所存储对象的 String
		 * newValue - 将使用此键存储的 Object
		 * MNEMONIC_KEY 用来存储对应于一个 KeyEvent 键代码的 Integer 值的键。
		 */
		putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_A));//Alt+A弹出关于对话框
		
		this.parentComponent = parentComponent;
	}

	public void actionPerformed(ActionEvent e) {
		JOptionPane.showMessageDialog(parentComponent, "关于Swing","About Box V2.0",JOptionPane.INFORMATION_MESSAGE);
	}
	
}


 

你可能感兴趣的:(14. 5. 2. 按钮事件及快捷键 Creating a JButton from an Action object)