I cannot understand why one of the following bits of code compiles and the other one doesn't.
The one that doesn't compile (Compiler says the method KeyBidings() needs a return type):
public KeyBidings(){
Action rightAction = new AbstractAction(){
public void actionPreformed(ActionEvent e){
x+=10;
drawPanel.repaint();
}
};
Action leftAction = new AbstractAction(){
public void actionPreformed(ActionEvent e){
x-=10;
drawPanel.repaint();
}
};
InputMap inputMap = drawPanel.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = drawPanel.getActionMap();
inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "rightAction");
actionMap.put("rightAction", rightAction);
inputMap.put(KeyStroke.getKeyStroke("LEFT"), "leftAction");
actionMap.put("leftAction", leftAction);
add(drawPanel);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(640, 480);
setTitle("Game");
setLocationRelativeTo(null);
setVisible(true);
}
And the one that compiles just fine:
public KeyBidings(){
Action rightAction = new AbstractAction(){
public void actionPerformed(ActionEvent e) {
x +=10;
drawPanel.repaint();
}
};
InputMap inputMap = drawPanel.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = drawPanel.getActionMap();
inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "rightAction");
actionMap.put("rightAction", rightAction);
add(drawPanel);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
EDIT: I didn't know the difference between a constructor and a method, but now i have another problem: https://gyazo.com/cd3c21a8562589451814903febaf89fe
What's the problem here? I've included the source codes for both classes below.
Source Code 1: http://pastebin.com/vwNtJZEG Source Code 2: http://pastebin.com/nL4SbtkM
The second one is the constructor of a class named KeyBidings, whereas the first one is a method, with a missing return type, of some other class.
Read the tutorial about constructors .
Note that the compiler doesn't say that the method may not be public, as your title says. It says that it must have a return type. That's quite different.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.