[英]What's the difference between these two bits of code?
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): 一个不会编译的(编译器说KeyBidings()方法需要返回类型):
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 编辑:我不知道构造函数和方法之间的区别,但现在我有另一个问题: 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 源代码1: http : //pastebin.com/vwNtJZEG源代码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. 第二个是名为KeyBidings的类的构造函数,而第一个是其他类的具有丢失的返回类型的方法。
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.
那是完全不同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.