I'm attempting to work with Java key bindings for the first time and am having trouble understanding how bindings connect to actions. My goal is to use an InputMap to connect a specific key to a JButton so that the button performs its normal function when that key is pressed. I am not using a Key Listener because I want this event to trigger when the window is focused, not just the button itself. (a WHEN_IN_FOCUSED_WINDOW
binding)
If I have this simple button:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class basicButton extends JFrame{
public static void main (String args[]) {
JButton button = new JButton("Button1");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button pressed");
}
});
basicButton t = new basicButton();
t.add(button);
t.setDefaultCloseOperation(EXIT_ON_CLOSE);
t.setSize(100, 100);
t.setVisible(true);
}
}
How do I make it print "button pressed" when the Insert key is pressed?