Not sure why, but when I try to use KeyEvents to make an ImageIcon move, it doesn't work. I want to, when I press the "A" key, have my image move left.
This is my code, polished by a helper:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class MainClass extends AbstractAction {
JLabel label;
int x = 300;
int y = 300;
public MainClass() {
final JPanel panel = new JPanel();
final ImageIcon image = new ImageIcon("Character Face Left - Bronze.png");
label = new JLabel(image,JLabel.CENTER );
label.setSize(500,500);
label.setLocation(x, y);
final JFrame frame = new JFrame( "Rover: Bound to Earth" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setLayout(null);
frame.add(label);
frame.setSize(500, 500);
frame.setVisible(true);
InputMap inputMap = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = panel.getActionMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "LEFT");
actionMap.put("LEFT", this);
}
@Override
public void actionPerformed(ActionEvent e) {
x -= 10;
label.setLocation(x, y);
}
public static void main( String[] args ) {
SwingUtilities.invokeLater( () -> { new MainClass(); } );
}
}
InputMap inputMap = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = panel.getActionMap();
You add the key bindings to the panel, but you never use the panel.
Key bindings should be added to the component you want to manipulate:
InputMap inputMap = label.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = label.getActionMap();
Or, if you really wanted to set the bindings on the panel, then you would need to add the label to the panel and then add the panel to the frame. So the frame would use the default BorderLayout and the panel would use the null layout.
Don't randomly set a size for a component:
label.setSize(500,500);
Instead you base the size on the preferred size:
label.setSize( label.getPreferredSize() );
Also, why are you extending AbstracAction?
public class MainClass extends AbstractAction {
The code in this class is used to create a GUI, you should not be extending an AbstractAction just for this.
Read the section from the Swing tutorial on How to Use Actions. The ActionDemo.java source code will show you how to better structure your code and use an Action as a separate inner class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With