0

I'm Trying to write a Simple Hangman game, so far i have managed to get the word length and the word chosen randomly. However i can't find the way to implement user input. The idea is that user inputs a letter in to JTextField and the XXX is substituted if the letter is guessed correctly. I would appreciate if someone can help me with sorting this out, please have a look at the code i have so far, also pleas note this is done in NetBeans.

static String [] words = { "dog", "java" };
int[] wordLength = new int[2];
String line = "",letter;    
int level = (int) (Math.random() * 2);    
int a = 0,b = 0, wrong=0;

private void btGuessActionPerformed(java.awt.event.ActionEvent evt) {                                        
    for (a = 0; a < 2; a++) {
        wordLength[a] = words[a].length();
    } 
    while (b < wordLength[level]) {
        line += " X";
        b++;
    }

    Letter0.setText(line);
    letter = uInput.getText();
    if (!words[level].contains(letter)) {
        wrong++;
        if (wrong == 1) {
            pbShow.setIcon(new javax.swing.ImageIcon("images/H0.png"));
        }
        if (wrong == 2) {
            pbShow.setIcon(new javax.swing.ImageIcon("images/H1.png"));
        }
        if (wrong == 3) {
            pbShow.setIcon(new javax.swing.ImageIcon("images/H2.png"));
        }
        if (wrong == 4) {
            pbShow.setIcon(new javax.swing.ImageIcon("images/H3.png"));
        }
        if (wrong == 5) {
            pbShow.setIcon(new javax.swing.ImageIcon("images/H4.png"));
        }
        if (wrong == 6) {
            pbShow.setIcon(new javax.swing.ImageIcon("images/H5.png"));
        }
        if (wrong == 7) {
            pbShow.setIcon(new javax.swing.ImageIcon("images/Hlost.png"));
        }              
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
tomaszsvd
  • 148
  • 2
  • 4
  • 15
  • 2
    http://www.tutorialspoint.com/swing/swing_jtextfield.htm Good example at the bottom – Steven Nov 28 '15 at 17:46
  • 1
    Use a DocumentListener. [For example](http://stackoverflow.com/questions/22803604/how-to-trigger-keyreleased-event-in-java-swing). – Hovercraft Full Of Eels Nov 28 '15 at 17:49
  • I need to check if the user input in to JTextField is equal to a stored String[] do you suggest that i should have all the conditios coded behind that text field and have a ActionListener[] getActionListeners() as array? – tomaszsvd Nov 28 '15 at 19:00

0 Answers0