最初我使用JMenu并建立快捷键来使用加速器。它完美地工作着。现在我想在JButton中实现相同的行为,但我卡住了。 这是我编写的代码:请分享您的想法,以便我可以走上正确的道路。
import javax.swing.*;
import java.awt.Event;
import java.awt.event.*;
import java.util.Arrays;
public class ShowDialogBox{
JFrame frame;
public static void main(String[] args){
ShowDialogBox db = new ShowDialogBox();
}
public ShowDialogBox(){
frame = new JFrame("Show Message Dialog");
// create an Action doing what you want
KeyStroke keySave = KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK);
Action performSave = new AbstractAction("Click Me") {
public void actionPerformed(ActionEvent e) {
//do your save
System.out.println("clickMe");
}
};
JButton button = new JButton("Click Me");
button.getActionMap().put("Click Me", performSave);
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keySave, "Click Me");
button.addActionListener(new MyAction());
frame.add(button);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction implements ActionListener{
public void actionPerformed(ActionEvent e){
String[] items = {
"1", "2", "3"
};
JList list = new JList(items);
JPanel panel = new JPanel();
panel.add(list);
JOptionPane.showMessageDialog(null, panel);
}
感谢您的提前帮助。
setAction(...)
并为Action设置适当的助记符即可轻松完成。您确定要使用控制键组合吗?如果是,请使用KeyEvent.CTRL_DOWN_MASK
而不是KeyEvent.CTRL_MASK
。 - Hovercraft Full Of Eels