Search code examples
javaswingjtextfield

How to get textfield that updates from listener in Java Swing for Hangman game?


I am trying to write a code from Hangman program. I am not sure if this idea is correct. I was thinking of having dashes (_ _ _ _ _) in textfield which must dynamically change when user presses buttons. for example, if the user presses button "A" in the below code, the the dashes should change to ( A _ _ _ _ ). That is the user has guessed the letter A correct.

I am still confused as how to implement this. Attaching eventListeners would be my next part. But for now, I have to get the basic GUI working, for which I need to an idea as how to implement entire thing.

what is the better way to get this working? here is my code as of now.

import javax.swing.*;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import java.awt.event.*;
import java.awt.image.BufferedImage;

public class HangmanGUI {

public HangmanGUI() {
    JFrame myframe= new JFrame();
    myframe.getContentPane().setLayout(new BorderLayout());
    JPanel myPanel = new JPanel();
    myPanel.setLayout(new GridLayout(2,15));
    myframe.setSize(600,600);

    for (char alphabet = 'A';alphabet<='Z';alphabet++){
        myPanel.add(new JButton(alphabet+""));
    }

    myframe.getContentPane().add(myPanel, BorderLayout.SOUTH);
    myframe.setTitle("Hangman Game");
    myframe.setVisible(true);
    myframe.setLocationRelativeTo(null);
    myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args){
    new HangmanGUI();
}
}

Solution

  • Yes use JFromattedTextFeild with a MaskFormatter class. MaskFormatter has a setPlaceholderCharacter('_') function to help you with. You may also need to use the InputVerifier to verify user input's validity. JFormattedTextFeild's documentation has example to show how to use an InputVerifier with it.