Initially I was using JMenu and establishing hot keys to work using accelerator. It was working perfectly. Now I want the same behavior in JButton but I am stuck. Here is the code that I wrote : Please share your ideas so I can go in the right path.
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);
}
Thanks in advance