java中菜单设置助记键,如何在Java中设置按钮单键助记符?

I am working on a project and I want to set Mnemonic on buttons. But the problem is Mnemonic works on pairing key example (Alt+F) etc. But I want it to be on single key.

解决方案

have look at KeyBindings,

then you can to attach any Key to the JButton

Here is one example code for your help, just Press C on the Keyboard :

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.Action;

public class ButtonExample

{

private JFrame frame;

private JButton button;

private void displayGUI()

{

frame = new JFrame("Button Mnemonic Example");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel contentPane = new JPanel();

Action buttonAction = new ButtonAction("CLICK ME"

, "This is a Click Me JButton");

button = new JButton(buttonAction);

button.getInputMap().put(KeyStroke.getKeyStroke('c'), "Click Me Button");

button.getActionMap().put("Click Me Button", buttonAction);

contentPane.add(button);

frame.setContentPane(contentPane);

frame.pack();

frame.setLocationByPlatform(true);

frame.setVisible(true);

}

class ButtonAction extends AbstractAction

{

public ButtonAction(String text, String desc)

{

super(text);

putValue(SHORT_DESCRIPTION, desc);

}

@Override

public void actionPerformed(ActionEvent ae)

{

JOptionPane.showMessageDialog(frame, "BINGO, you SAW me.");

}

}

public static void main(String... args)

{

SwingUtilities.invokeLater(new Runnable()

{

public void run()

{

new ButtonExample().displayGUI();

}

});

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值