I have what appears to be a somewhat unique problem. I'm currently trying to code mouse events into my program, a game engine of sorts. My problem is:
When the mouse is clicked/released, I want to evoke code that has already been written as an Action for the Enter key.
In my Binds class, I link enter to my action as such:
public class Binds extends InputMap
{
public Binds(JPanel object)
{
// InputMap stuff
InputMap inputMap = object.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "ESCAPE");
}
}
With the corresponding ActionMap:
ActionMap actionMap = game.getActionMap(); //game is an object which extends JPanel.
actionMap.put("ENTER", new AbstractAction(){
@Override
public void actionPerformed(ActionEvent e)
{
//A very excessive amount of code
}
}
I do not want to copy-paste the code in the ActionMap, and would like to keep the code simple. Is there any way that I could link my MouseEvent/MouseListener such that it manually executes this code?
Two methods I have thought of, but can't implement include:
I have tried finding ways of doing both, but there seems to be no way of doing so. Also, I do not have ActionListeners in my code. I use them with my JButtons, but not my key bindings. If you need any additional information, please let me know.
What would I be able to do? Thank you so much for your help.
Move the code to a private method:
private void doAction() {
//A very excessive amount of code
}
Then call that method from both your ActionMap and your MouseListener methods:
actionMap.put("ENTER",
new AbstractAction() {
private static final long serialVersionUID = 1;
@Override
public void actionPerformed(ActionEvent event) {
doAction();
}
});
gamePanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent event) {
doAction();
}
});