如何在Java Swing for Hangman游戏中获取从监听器更新的文本字段? [英] How to get textfield that updates from listener in Java Swing for Hangman game?

查看:81
本文介绍了如何在Java Swing for Hangman游戏中获取从监听器更新的文本字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写Hangman程序的代码。我不确定这个想法是否正确。我想在文本字段中使用短划线(_ _ _ _ _),当用户按下按钮时必须动态更改。例如,如果用户在下面的代码中按下按钮A,则破折号应改为(A _ _ _ _)。那是用户猜对了字母A是正确的。

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.

我仍然对如何实现这一点感到困惑。附加eventListeners将是我的下一个部分。
但是现在,我必须得到基本的GUI工作,我需要一个想法,如何实现整个事情。

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();
}
}


推荐答案

是使用 JFromattedTextFeild MaskFormatter 类。 MaskFormatter 有一个 setPlaceholderCharacter('_')函数来帮助你。您可能还需要使用 InputVerifier 验证用户输入的有效性。 JFormattedTextFeild的文档中有一个示例,说明如何使用 InputVerifier

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.

这篇关于如何在Java Swing for Hangman游戏中获取从监听器更新的文本字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆