Java Hangman - 如何在单击时为JButton分配字母?

时间:2012-11-11 16:37:37

标签: java arrays netbeans jbutton

我在Netbeans上制作了一个基本的刽子手游戏,它的工作方式是用户点击26个按钮中的一个(每个字母对应一个字母),并在单词中测试该字母。我遇到的主要问题是让这封信得到测试。

    //array holding all buttons        
    JButton[] alphabet = {AButton, BButton, CButton, DButton, EButton, FButton, GButton, HButton, IButton, JButton, KButton, LButton, MButton, NButton, OButton, PButton, QButton, RButton, SButton, TButton, UButton, VButton, WButton, XButton, YButton, ZButton};

    //getting the current letter(need something in place of the 0)
    String currentLetter = (alphabet[0].getLabel());             

    //replace underscores with letters as they are guessed
                for (int i = 0; i < 1; i++) {
                    secretWord = secretWord + currentLetter.charAt(0);
                    foundWord = words[randValue].replaceAll("[^" + secretWord + "]", "_ ");
    }

我在某处读到使用按钮数组是我必须要做的事情,所以我把它放进去但它没有用。另外,我读到程序需要一个ActionListener来读取它是什么字母。我之前尝试过的尝试是:

currentLetter = AButton.getText();

currentLetter = AButton.getLabel();

但遗憾的是无济于事。所以请记住,我使用的是Netbeans,而且我是Java的新手,所以没有大的精心设计的东西,保持简单。感谢:)

编辑:

        private void AButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
        DoButton.doClick();
}                                       

        private void DoButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            JButton button = (JButton) evt.getSource();
            String currentLetter = button.getText(); 

        //replace underscores with letters as they are guessed
                        for (int i = 0; i < 1; i++) {
                            secretWord = secretWord + currentLetter.charAt(0);
                            foundWord = words[0].replaceAll("[^" + secretWord + "]", "_ ");
               }
    }

完整代码:

    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Random;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.UIManager;
    import javax.swing.plaf.FontUIResource;

    public class MainFrame extends javax.swing.JFrame {

        public MainFrame() {
            initComponents();
        }

        static String secretWord = "";
        StringBuilder mainWord = new StringBuilder();
        String[] words =         {"technology", "computer", "camera", "graphic", "digital", "media", "technician",
            "photography", "troubleshoot", "pixels", "application", "download"};
        Random r = new Random();
        int randValue = r.nextInt(11)+1;
        String guessWord = words[0];//words[randValue];
        int errors = 0;
        public static int wins = 0, losses = 0;
        String foundWord = null;
        String currentLetter;
        private void RestartButtonActionPerformed(java.awt.event.ActionEvent evt)         {                                              
            //restart game
                DirectionsFrame DFrame = new DirectionsFrame();
                DFrame.setVisible(true);
                setVisible(false);
                MainFrame MFrame = new MainFrame();
                MFrame.dispose();
                secretWord = "";
                foundWord = null;
                DirectionsFrame.WinsLabel.setText(null);
                DirectionsFrame.LossesLabel.setText(null);
        }                                             

        private void GetButtonActionPerformed(java.awt.event.ActionEvent evt)         {                                          
            for (int i = 0; i < guessWord.length(); i++) {
                mainWord.append("_ ");
            }
            String SetMain = mainWord.toString();
            mainWord.append(secretWord);
            WordLabel.setText(SetMain);
            GetButton.setEnabled(false);
            AButton.setEnabled(true);BButton.setEnabled(true);CButton.setEnabled        (true);DButton.setEnabled(true);EButton.setEnabled(true);
            FButton.setEnabled(true);GButton.setEnabled(true);HButton.setEnabled        (true);IButton.setEnabled(true);JButton.setEnabled(true);
    KButton.setEnabled(true);LButton.setEnabled(true);MButton.setEnabled(true);NButton.setEnabled(true);OButton.setEnabled(true);
    PButton.setEnabled(true);QButton.setEnabled(true);RButton.setEnabled(true);SButton.setEnabled(true);TButton.setEnabled(true);
    UButton.setEnabled(true);VButton.setEnabled(true);WButton.setEnabled(true);XButton.setEnabled(true);YButton.setEnabled(true);
    ZButton.setEnabled(true);
}                                         

private void ExitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // Exit the program
    System.exit(0);
}                                          

private void AButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void BButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void CButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void DButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void EButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void FButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void GButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void HButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void IButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void JButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void KButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void LButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void MButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void NButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void OButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void PButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void QButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void RButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void SButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void TButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void UButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void VButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void WButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void XButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void YButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void ZButtonActionPerformed(java.awt.event.ActionEvent evt) {                                        
    DoButton.doClick();
}                                       

private void DoButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
    JButton button = (JButton) evt.getSource();
    String currentLetter = button.getText(); 

//replace underscores with letters as they are guessed
            do {
                for (int i = 0; i < 1; i++) {
                    secretWord = secretWord + currentLetter.charAt(0);
                    foundWord = words[0].replaceAll("[^" + secretWord + "]", "_ ");
                //if letter isn't in word
                    if (guessWord.indexOf(currentLetter) == -1) {
                        JOptionPane.showMessageDialog(null, "Sorry, that wasn't in the word.");
                        errors++;
                        if (errors == 1) {
                            Hangman0.setVisible(false);
                        }
                        if (errors == 2) {
                            Hangman1.setVisible(false);
                        }
                        if (errors == 3) {
                            Hangman2.setVisible(false);
                        }
                        if (errors == 4) {
                            Hangman3.setVisible(false);
                        }
                        if (errors == 5) {
                            Hangman4.setVisible(false);
                        }
                        if (errors == 6) {
                            Hangman5.setVisible(false);
                        }
                        if (errors == 7) {
                            Hangman6.setVisible(false);
                        }
                        if (errors == 8) {
                            Hangman7.setVisible(false);
                        }
                        if (errors == 9) {
                            Hangman8.setVisible(false);
                        }
                        if (errors == 10) {
                            Hangman9.setVisible(false);
                            JOptionPane.showMessageDialog(null, "You lost! The word was: " + guessWord);
                            losses++;
                            DirectionsFrame DFrame = new DirectionsFrame();
                            DFrame.setVisible(true);
                            setVisible(false);
                            MainFrame MFrame = new MainFrame();
                            MFrame.dispose();
                            secretWord = "";
                            foundWord = null;
                            String strLosses = Integer.toString(losses);
                            String strWin = Integer.toString(wins);
                            DirectionsFrame.WinsLabel.setText(strWin);
                            DirectionsFrame.LossesLabel.setText(strLosses);
                        }
            }
        }
                WordLabel.setText(foundWord.toUpperCase());
            } while (foundWord == null);
            if (foundWord.equalsIgnoreCase(guessWord)) {
                JOptionPane.showMessageDialog(null, "Yay!");
                wins++;
                DirectionsFrame DFrame = new DirectionsFrame();
                DFrame.setVisible(true);
                setVisible(false);
                MainFrame MFrame = new MainFrame();
                MFrame.dispose();
                secretWord = "";
                foundWord = null;
                String strWin = Integer.toString(wins);
                String strLosses = Integer.toString(losses);
                DirectionsFrame.WinsLabel.setText(strWin);
                DirectionsFrame.LossesLabel.setText(strLosses);
            }
}                                        

3 个答案:

答案 0 :(得分:3)

创建一个动作监听器:

ActionListener al = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        Object src = evt.getSource();
        if (evt instanceof JButton) {
            currentLetter = ((JButton) src).getText();
            // do something with letter
        } // else something seriously wrong
    }
};

然后将此动作侦听器添加到alphabet中的每个按钮:

for (JButton button : alphabet) {
    button.addActionListener(al);
}

编辑我没有在更新的代码中看到initComponents()的实施。无论如何,为每个按钮添加动作侦听器只需要执行一次。这是我将如何开始实施initComponents()

private static String[] letters = { "A", "B", "C", "D", "E", "F",
    "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
    "S", "T", "U", "V", "W", "X", "Y", "Z" };
private JButton[] letterButtons = new JButton[letters.length];

private void initComponents() {
    ActionListener al = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            Object src = evt.getSource();
            if (evt instanceof JButton) {
                currentLetter = ((JButton) src).getText();
                // do something with letter
            } // else something seriously wrong
        }
    };
    for (int i = 0; i < letters.length; ++i) {
        letterButtons[i] = new JButton(letters[i]);
        letterButtons[i].addActionListener(al);
    }
    . . .
    // add all the buttons to the user interface
    . . .
}  

请使用更多阵列简化您的代码!我当然不会为每个字母按钮或26个单独的方法单独处理每个字母单击的单独变量。

答案 1 :(得分:1)

是的,单个ActionListener可用于每个按钮,不仅可以确定已点击的内容,还可以确定其文本。在你的听众中,你可以使用:

public void actionPerformed(ActionEvent e) {
    JButton button = (JButton) e.getSource();
    String currentLetter = button.getText(); 
    updateWord(currentLetter);
}

知道currentLetter后,您可以将其传递给辅助方法,例如updateWord以显示必要的字符等。

private void updateWord(String currentLetter) {
 // reveal letters
 // increment 'Hangman' guess counter
}

请阅读How to Write an Action Listener

另请考虑使用Action在按钮之间共享功能。

答案 2 :(得分:0)

一个好的解决方案不会使用'AButton','BButton'之类的东西。

正如您所提到的,您可以使用Button-Array(长度为26)完成所有操作!

在循环中初始化它,创建26个按钮实例,并注册一个ActionListener(总是相同,而不是26)。

你可以从Array-Index获得相应的字母!

如何?拿ASCII表。假设您只想使用大字母,A的值为65。

所以每个按钮对应字母

  

65 + indexOf(按钮)

     

按钮[0] - &gt; 65 + 0 ='A'按钮[1] - &gt; 65 + 1 ='B'

你明白了。

单个ActionListener可以使用相同的方法来获取相应的字母: 类似的东西:

  

char theLetter =(char)65 + buttonArray.indexOf(e.getSource())

你已经完成了。

我认为编程不是以某种方式完成它。你总是应该寻找完美的解决方案。如果这个解决方案对您来说很难,您应该学习如何做到这一点。

问候!