Search code examples
javajframejlabeljtextfield

How can I fill in letters to blank space in Hangman Game if word contains letter?


enter image description hereI'm making a hangman game and I'm stumped on how I can fill the letter into the correct blank space if the word contains the letter. For example:

word: hello

blank spaces: _ _ _ _ _

user input: e

blank spaces: _ e _ _ _

Here is all my code, it is not an SSCCE but I've uploaded the image to along with this post.If you have any suggestions, please say. Thanks.

    package Game;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;

class GameStructure {
    private String []wordList = {"javatar","java","activity","alaska","appearance","article",
            "automobile","basket","birthday","canada","central","character","chicken","chosen",
            "cutting","daily","darkness","diagram","disappear","driving","effort","establish","exact",
            "establishment","fifteen","football","foreign","frequently","frighten","function","gradually",
            "hurried","identity","importance","impossible","invented","italian","journey","lincoln",
            "london","massage","minerals","outer","paint","particles","personal","physical","progress",
            "quarter","recognise","replace","rhythm","situation","slightly","steady","stepped",
            "strike","successful","sudden","terrible","traffic","unusual","volume","yesterday"};
   private JTextField tf;
   private JLabel jl2;
   static String letter;
   static int []length = new int[64];

   public void window() {
       JMenuBar menuBar = new JMenuBar();
       JMenu menu = new JMenu("File");
       menu.setMnemonic(KeyEvent.VK_A);
       menuBar.add(menu);
       JMenuItem menuItem = new JMenuItem("Developer", KeyEvent.VK_T);
    menu.add(menuItem);
    JMenuItem menuItem2 = new JMenuItem("Instructions", KeyEvent.VK_T);
    menu.add(menuItem2);
    JMenuItem menuItem3 = new JMenuItem("Restart", KeyEvent.VK_T);
    menu.add(menuItem3);
    JMenuItem menuItem4 = new JMenuItem("Exit", KeyEvent.VK_T);
    menu.add(menuItem4);

       ImageIcon ic = new ImageIcon("hangman2.png");
      JFrame gameFrame = new JFrame();
      JPanel bottomRight = new JPanel();
      JPanel bottomLeft = new JPanel();
      JPanel top = new JPanel();
      JPanel bottom = new JPanel();
      JPanel imgPane = new JPanel();
      JPanel panel1 = new JPanel();
      bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));
      imgPane.setLayout(new BorderLayout());
      panel1.setLayout(new BorderLayout());
      panel1.setOpaque(false);//!!
      top.setBorder(BorderFactory.createTitledBorder(""));
      bottom.setBorder(BorderFactory.createTitledBorder(""));
      tf = new JTextField(1);
      JLabel img = new JLabel(ic, JLabel.CENTER);
      JLabel jl = new JLabel("Enter a letter", JLabel.CENTER);
      jl2 = new JLabel("Letters used:  ", JLabel.CENTER);
      JLabel jl3 = new JLabel("__ ", JLabel.CENTER);
      jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
      tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
      jl2.setFont(new Font("Rockwell", Font.PLAIN, 20));
      imgPane.add(img);//center
      top.add(jl);//top center
      top.add(tf);//top center
      bottomLeft.add(jl2);//bottom left position
      bottomRight.add(jl3);//bottom right position
      bottom.add(bottomLeft);//bottom
      bottom.add(bottomRight);//bottom
      panel1.add(imgPane, BorderLayout.CENTER);//background image (center)
      panel1.add(top, BorderLayout.NORTH);//text field and jlabel (top)
      panel1.add(bottom, BorderLayout.SOUTH);// blank spaces and letters used (bottom)
      gameFrame.setJMenuBar(menuBar);
      gameFrame.setTitle("Hangman");
      gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      gameFrame.setIconImage(
      new ImageIcon("hangmanIcon.png").getImage());
      gameFrame.setResizable(false);
      gameFrame.add(panel1);
      gameFrame.setSize(800, 500);
      gameFrame.setLocationRelativeTo(null);
      gameFrame.setVisible(true);

          int j = 0;
          for(j = 0; j<64; j++) {
             length[j] = wordList[j].length();//gets length of words in wordList
          }//end for
          int l = 0;
          String line = "";
          //create line first then put into .setText
          for(int m = 0; m<length[l]; m++) {
              line += "__ ";
              l++;
          }//end for
          jl3.setText(line);


          tf.addActionListener(new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {//when enter key pressed
              JTextField tf = (JTextField)e.getSource();
             letter = tf.getText();
              jl2.setText(jl2.getText() + letter + " ");//sets jlabel text to users entered letter

              int k = 0;
              for(k = 0; k<64;){
                  if(wordList[k].contains(letter)){
                      System.out.println(letter);
                     break;
                  }else{
                      System.out.println("letter not in word");
                      break;
                  }
              }

              }//end actionPerformed method
          });
      }//end window method
   }

public class GameMain {
   public static void main(String[] args) {
      GameStructure game = new GameStructure();
      game.window();
   }
}

Solution

  • Well, you can get the text of your JLabel with getText(), then edit the String, and then apply the result with setText(String).

    You just have to calculate the correct positions where you should insert the letters.

    char[] jlabelText = yourJLabel.getText().toCharArray();
    
    for (int i = 0; i < word.length(); i++) {
        if (word.charAt(i) == userEnteredChar) {
            jlabelText[3 * i] = ' ';
            jlabelText[3 * i + 1] = userEnteredChar;
        }
    }
    
    yourJLabel.setText(String.valueOf(jlabelText));