如何在不调用类的情况下引用类?

时间:2015-12-30 05:43:16

标签: java class methods actionlistener keylistener

我正在制作一个刽子手游戏,但真正造成问题的是我的方法PanDisp和我的班级LabelChangeListener。我想将KeyListenerActionListener添加到各个类(KeyInputLabelChangeListener),但是当我这样做时,我需要引用它们所在的类,我运行程序后得到StackOverflowError,因为当我调用该类时,我会陷入无限循环,不断调用LabelChangeListener然后调用PanDisp()

我的问题是如何引用这些类并添加各自的侦听器而不在循环中调用它们?

public class PanDisp extends JPanel {

    JLabel lblOutput;
    JLabel lblGuess;
    JButton btnUpdateLabel;
    Image imgPkmn;
    FraImg fraImg;
    String sSecret;

    public PanDisp() {//Constructor
        KeyInput keyInput = new KeyInput();
        KeyInput.LabelChangeListener labelChange = keyInput.new LabelChangeListener();
        sSecret = "*******";
        lblGuess = new JLabel("Type will go here");
        lblOutput = new JLabel(sSecret);
        btnUpdateLabel = new JButton("Enter");
        add(lblOutput);
        add(btnUpdateLabel);
        addKeyListener(new KeyInput());
        setFocusable(true);
        btnUpdateLabel.addActionListener(labelChange);
        fraImg = new FraImg(imgPkmn);
        //fraImg.main();
    }

    public void GameOver() {

    }

    class KeyInput implements KeyListener {

        String sInput;
        String sWord = "pikachu";
        String sSecret = "*******";
        char chInput;

        /*keyPressed - when the key goes down
        keyReleased - when the key comes up
        keyTyped - when the unicode character represented by this key is sent by the keyboard to system input.*/
        @Override
        public void keyTyped(KeyEvent e) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void keyPressed(KeyEvent e) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            chInput = (char) e.getKeyChar();
            sInput = String.valueOf(chInput); // convert the char to a String
            lblOutput.setText(sInput);
        }

        @Override
        public void keyReleased(KeyEvent e) {

        }

        class LabelChangeListener implements ActionListener {

            char cWord;
            int nCorrect, nIncorrect, nNum;
            PanDisp panDisp = new PanDisp();

            public void actionPerformed(ActionEvent event) {

                if (sWord.contains(sInput)) {
                    for (int i = 0; i < sWord.length(); i++) {
                        sSecret.replace(sSecret.charAt(i), sWord.charAt(i));

                    }

                }

            }
        }
    }
}

0 个答案:

没有答案