Original Post
I am trying to setMnemonic to some JButtons but it always adds the alt as its the default mouseless operator. What can I do to remove the alt, change it to ctrl or any other mask etc. Thanks!
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;import javax.swing.JPanel;import javax.swing.KeyStroke;import javax.swing.SwingUtilities;public class ActionExample { public static void main(String[] args) { new ActionExample(); } public ActionExample(){ SwingUtilities.invokeLater(new Runnable(){ public void run(){ initGui(); } }); } private void initGui(){ //Prepare the frame JFrame frame = new JFrame("Action Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Prepare a panel to hold the two buttons JPanel panel = new JPanel(); frame.getContentPane().add(panel); //Set up button1 JButton button1 = new JButton("Button1 (ctrl+1)"); //Create an action for buttons1. //I could have created one action for both buttons and used e.getSource() to find which button was the source of the event. Action button1Action = new AbstractAction(){ public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "You activated button1"); } }; //Set up the mappings so that key events get mapped to actions //The string can actually be any object that is different for each action. I just used these strings for ease since "b1a" is different than "b2a". button1.getInputMap(JOptionPane.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_1, KeyEvent.CTRL_DOWN_MASK), "b1a"); button1.getActionMap().put("b1a", button1Action); //An action is a subclass of ActionListener, so we can do the following: button1.addActionListener(button1Action); //Add the button to the panel panel.add(button1); //Set up button2 JButton button2 = new JButton("Button2 (ctrl+2)"); Action button2Action = new AbstractAction(){ public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "You activated button2"); } }; button2.getInputMap(JOptionPane.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_2, KeyEvent.CTRL_DOWN_MASK), "b2a"); button2.getActionMap().put("b2a", button2Action); button2.addActionListener(button2Action); panel.add(button2); //Add the finishing touches on the frame frame.pack(); frame.setVisible(true); }}This topic has been locked by a moderator. New replies are not allowed.
With your permission, GameDev.net uses analytics cookies to understand how people use the platform. You can accept analytics or continue with necessary cookies only. Learn more