I'm trying to integrate keybindings into a program I'm making, but as that program is long, I'm trying to learn on a smaller similarly coded program that I found on StackOverflow.
Here's the code I'm using:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Demo {
@SuppressWarnings("serial")
private void initGUI() {
JPanel content = new JPanel(new FlowLayout());
content.add(new JLabel("Test:"));
AbstractAction buttonPressed = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
System.out.println(e.getSource());
if ("a".equals(e.getActionCommand()))
content.setBackground(new Color(227, 19, 19));
if ("b".equals(e.getActionCommand()))
content.setBackground(new Color(0, 225, 19));
}
};
JButton submit = new JButton("Submit");
submit.addActionListener(buttonPressed);
submit.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(
javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_A,
java.awt.event.InputEvent.CTRL_DOWN_MASK),
"A_pressed");
submit.getActionMap().put("A_pressed", buttonPressed);
submit.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(
javax.swing.KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_B, 0),
"B_pressed");
submit.getActionMap().put("B_pressed", buttonPressed);
content.add(submit);
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(content);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Demo().initGUI();
}
});
}
}
What I what to happen is to press CTRL+A and have the background change color. However, when I do this, System.out.println(e.getActionCommand())
is returning a character that looks like a question mark in a box like it's an unknown character or something. The program works if you press B, but adding the modifier CTRL is not working correctly.
Is the problem something I'm not doing right? Is the program working correctly and I don't know how to compare e.getActionCommand()
and what ever string CTRL+A returns as a ActionEvent? Please help.