这两段代码有什么区别?

时间:2016-04-06 19:23:32

标签: java

我无法理解为什么下面的一些代码编译而另一个没有编译。

不编译的那个(编译器说方法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);
}

编译得很好的那个:

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);
}
编辑:我不知道构造函数和方法之间的区别,但现在我有另一个问题:https://gyazo.com/cd3c21a8562589451814903febaf89fe

这里有什么问题?我在下面列出了两个类的源代码。

源代码1:http://pastebin.com/vwNtJZEG 源代码2:http://pastebin.com/nL4SbtkM

1 个答案:

答案 0 :(得分:2)

第二个是名为KeyBidings的类的构造函数,而第一个是一个方法,缺少其他类的返回类型。

阅读the tutorial about constructors

请注意,编译器并未说明该方法可能不公开,正如标题所示。它说它必须有一个返回类型。那是完全不同的。

相关问题