如何为一个JButton添加快捷键?

miwoo 2002-11-29 09:01:24
如何为一个JButton添加快捷键?
...全文
415 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
XKP 2002-11-29
  • 打赏
  • 举报
回复
setMnemonic(int mnemonic)
Sets the keyboard mnemonic on the current model.
mercury1231 2002-11-29
  • 打赏
  • 举报
回复
修改一下加速健不就得了?
alphazhao 2002-11-29
  • 打赏
  • 举报
回复
这种设置快捷键必须同时按上Ctrl键
很不方便
给你个设置单键快捷键的实例,自个调用一下就明白了
import javax.swing.*;
import java.awt.*;
import com.borland.jbcl.layout.*;
import javax.swing.border.*;
import java.awt.event.*;
/**
* 作者:alphazhao
* 日期:2002-5-29
* 描述:确定修改备注时,弹出此确定窗口
* 其它:相关注释说明同ShowSelectByName.java
* */

public class ShowUpdateMsg extends JDialog {
private TitledBorder titledBorder1;
private String strMsg;
private Font font14 = new Font("Dialog", 0, 14);
private JPanel jPanel1 = new JPanel();
private XYLayout xYLayout1 = new XYLayout();
private JLabel jLabel1 = new JLabel();
private JButton jButton1 = new JButton();
private JButton jButton2 = new JButton();

public ShowUpdateMsg(Dialog owner, boolean modal) {
super(owner,modal);
try {
this.setTitle("系统提示");
this.setResizable(false);
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
jPanel1.setLayout(xYLayout1);
jLabel1.setFont(font14);
jLabel1.setText("是否确定要修改记录?");

jButton1.setFont(font14);
jButton1.setText("确 定");

jButton2.setFont(font14);
jButton2.setText("取 消");
this.setSize(350,130);

this.getContentPane().add(jPanel1, BorderLayout.CENTER);
jPanel1.add(jLabel1, new XYConstraints(94, 22, 221, 35));
jPanel1.add(jButton1, new XYConstraints(91, 65, 75, 25));
jPanel1.add(jButton2, new XYConstraints(180, 65, 75, 25));

SymListener symListener = new SymListener();
jButton1.addActionListener(symListener);
jButton2.addActionListener(symListener);
//设置快捷键
jButton1.registerKeyboardAction(symListener,
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
JComponent.WHEN_IN_FOCUSED_WINDOW);
//确定按钮为回车键"ENTER"
jButton2.registerKeyboardAction(symListener,
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
JComponent.WHEN_IN_FOCUSED_WINDOW);
//取消按钮为退出键"Escape"
}

void jButton1_actionPerformed(ActionEvent e) {
this.dispose();
}
void jButton2_actionPerformed(ActionEvent e) {
this.dispose();
}

///设置快捷键
class SymListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if (obj == jButton1) {
jButton1_actionPerformed(e);
}
else if (obj == jButton2) {
jButton2_actionPerformed(e);
}
}
}
}
//end

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧