在JTextArea中显示字符串数组

时间:2014-11-19 00:07:08

标签: java arrays user-interface

我一直坚持让我的一个JTextArea显示一个字符串数组,代表一个刽子手游戏中的单词中的字母。一旦用户猜出一个字母(假设它是正确的),它应该反映到数组中。相反,它似乎只是添加了猜测的字母,而不是空白或数组的其余部分。我想将猜测的字母设置为等于数组中的正确索引,然后将其显示在屏幕上。这是我的代码:

import javax.swing.*;

import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

@SuppressWarnings("serial")
public class GuiClass extends JFrame {

char guess = ' ';
int numGuesses = 0;
char[] letterGuessedAgainst = null;
String wordInPlay = " ";
String[] hangmanScores = null;
ArrayList<Character> wrongGuesses = null;
boolean isGuessSuccessfull = false;

private Container contents;
JRadioButton rbEasy;
JRadioButton rbHard;
ButtonGroup difficultyGroup;
JTextField txtfldWord;
JTextArea txtareaWord;
JLabel difficultyPrompt;
JLabel userDifficulty;
JButton btnStartGame;
JButton btnGuessSubmit;
JButton btnWordGuessSubmit;
JPanel topPanel;
JPanel midPanel;
JLabel topLabel;
JPanel guessPanel;
JPanel letterPanel;
JLabel word;
JTextArea txtareaNumGuesses;
JTextField txtfldGuess;
JTextField txtfldWordGuess;
JTextArea txtareaguessedLetters;
JTextArea txtareaLettersLeft;

public GuiClass(){
    super("Hangman GUI");

    contents = getContentPane();

    //create a new panel & set layout
    midPanel = new JPanel();
    midPanel.setLayout(new GridLayout(3,3));

    //layout manager
    topLabel = new JLabel("Welcome to Hangman!");
    contents.setLayout(new FlowLayout());

    //create new ButtonHandlers
    ButtonHandler buttonHandler = new ButtonHandler();
    ButtonHandler2 btnHndlrNewGame = new ButtonHandler2();

    //create difficulty buttons/labels & add ActionListeners
    difficultyPrompt = new JLabel("First, Choose A Difficulty:");

    rbEasy = new JRadioButton("Easy");
    rbHard = new JRadioButton("Hard");
    userDifficulty = new JLabel("Game Difficulty: ");
    difficultyGroup = new ButtonGroup();

    difficultyGroup.add(rbEasy);
    difficultyGroup.add(rbHard);

    rbEasy.addItemListener(buttonHandler);
    rbHard.addItemListener(buttonHandler);

    midPanel.add(topLabel);
    midPanel.add(difficultyPrompt);
    midPanel.add(rbEasy);
    midPanel.add(rbHard);
    midPanel.add(userDifficulty);

    topPanel = new JPanel();
    JLabel btnStartNewGame = new JLabel("Next, Start a new game!");
    btnStartGame = new JButton("Start A New Game");
    btnStartGame.addActionListener(btnHndlrNewGame);

    topPanel.add(btnStartNewGame);
    topPanel.add(btnStartGame);     

    guessPanel = new JPanel();
    JLabel lblGuess = new JLabel("Guess: ");
    JLabel lblWordGuess = new JLabel("Word Guess: ");

    btnGuessSubmit = new JButton("Submit");
    btnGuessSubmit.addActionListener(btnHndlrNewGame);

    btnWordGuessSubmit = new JButton("Submit");
    btnGuessSubmit.addActionListener(btnHndlrNewGame);

    txtfldGuess = new JTextField(10);
    txtfldWordGuess = new JTextField(10);

    guessPanel.add(lblGuess);
    guessPanel.add(txtfldGuess);
    guessPanel.add(btnGuessSubmit);

    guessPanel.add(lblWordGuess);
    guessPanel.add(txtfldWordGuess);
    guessPanel.add(btnWordGuessSubmit);

    letterPanel = new JPanel();
    JLabel lblGuessedLetters = new JLabel("Guessed Letters:");
    JLabel lblLettersInWord = new JLabel("Letters Left:");
    JLabel lblNumGuesses = new JLabel("Guess Number: ");

    txtareaNumGuesses = new JTextArea(5,5);
    txtareaNumGuesses.setEditable(false);

    txtareaguessedLetters = new JTextArea(5,15);
    txtareaguessedLetters.setEditable(false);

    txtareaLettersLeft = new JTextArea(5,15);
    txtareaLettersLeft.setEditable(false);

    letterPanel.add(lblGuessedLetters);
    letterPanel.add(txtareaguessedLetters);
    letterPanel.add(lblLettersInWord);
    letterPanel.add(txtareaLettersLeft);
    letterPanel.add(lblNumGuesses);
    letterPanel.add(txtareaNumGuesses);

    JPanel wordPanel = new JPanel();
    word = new JLabel("Word is: ");
    //txtfldWord = new JTextField(10);
    txtareaWord = new JTextArea(20,20);
    //txtfldWord.setEditable(false);
    txtareaWord.setEditable(false);
    wordPanel.add(word);
    //wordPanel.add(txtfldWord);
    wordPanel.add(txtareaWord);

    //add contents of panels to the container
    contents.add(midPanel);
    contents.add(topPanel);
    contents.add(guessPanel);
    contents.add(letterPanel);
    contents.add(wordPanel);

    setSize(800,600);
    setVisible(true);
}//end constructor

private class ButtonHandler implements ItemListener{
    public void itemStateChanged(ItemEvent ie){
        if (ie.getSource()==rbEasy){
            userDifficulty.setText("Game Difficulty: Easy");
        }//end if

        if (ie.getSource()==rbHard){
            userDifficulty.setText("Game Difficulty: Hard");
        }//end if

    }//end method
}//end ButtonHandler inner class

private class ButtonHandler2 implements ActionListener{
    public void actionPerformed(ActionEvent ae){
        if (ae.getSource()==btnStartGame){
            if (rbEasy.isSelected()){
                ArrayList<String> easyHmWords = new ArrayList<String>();
                String filename = "easyhangmanwords.txt";
                BufferedReader infile = null;
                try {
                    infile = new BufferedReader(new FileReader(filename));
                }//end try
                catch (FileNotFoundException e) {
                    e.getMessage();
                }//end catch

                String re = "";
                try {
                    while ((re=infile.readLine())!=null){ // reading one line
                        easyHmWords.add(re);
                    }//end while
                    System.out.println("words in file: "+easyHmWords);
                }//end try
                catch (IOException e) {
                    e.getMessage();
                }//end while
                try {
                    infile.close();
                }//end try
                catch (IOException e) {
                    e.getMessage();
                }//end catch

                wordInPlay = "";
                int randomNumber = 0;
                Random rand = new Random();
                int maxRandomNumber = 0;

                word.setText("Word is: Set");
                //System.out.println("Okay, the word is set!");
                maxRandomNumber = easyHmWords.size();
                System.out.println("Size of arraylist: "+easyHmWords.size());
                randomNumber = rand.nextInt(maxRandomNumber);
                System.out.println("random num: "+randomNumber);
                wordInPlay = easyHmWords.get(randomNumber);
                System.out.println("word in play: "+wordInPlay);

                //figures out how many letters the word has
                int lettersInWord = wordInPlay.length();
                System.out.println("Letters in word: "+lettersInWord);

                //creates an array of hangman scores which is the size of the letters in the word
                hangmanScores = new String[lettersInWord];

                //for loop to iterate through the array and assign "_" to the spaces
                for (int i = 0; i < hangmanScores.length; i++) {
                    hangmanScores[i] = " _ ";
                }//end for

                for (int i = 0; i < hangmanScores.length; i++){
                    //txtareaWord.setText(hangmanScores[i]);
                    //txtfldWord.append(hangmanScores[i]);
                    txtareaWord.append((hangmanScores[i]));
                }//end for

            }//end if
        }//end if

        if(btnGuessSubmit == ae.getSource()){ //getting problems in this if statement
            guess = txtfldGuess.getText().charAt(0);
            letterGuessedAgainst = wordInPlay.toCharArray();

            for (int i = 0; i < letterGuessedAgainst.length; i++) {//goes through the letters of the word in play
                ***if(letterGuessedAgainst[i]==guess){//if a letter matches up,
                    hangmanScores[i] = Character.toString(guess);
                    isGuessSuccessfull = true;
                }//end if
            }//end for

            for (int k =0; k < hangmanScores.length; k++){//displays the ______ in the text area
                txtareaWord.setText((hangmanScores[k]));***

                System.out.print(hangmanScores[k]);//testing purposes
            }//end for

            numGuesses++;
            txtareaNumGuesses.setText(" "+numGuesses);

        }//end for
        if(isGuessSuccessfull = false){
            wrongGuesses.add(guess);
            txtareaguessedLetters.append(wrongGuesses+"");

        }//end if
    }//end method
}//end private inner class

public static void main (String[] args){
    GuiClass estGUI = new GuiClass();
    estGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//end main method
}//end class

这是代码中不显示数组正确部分的部分:

                ***if(letterGuessedAgainst[i]==guess){//if a letter matches up,
                    hangmanScores[i] = Character.toString(guess);
                    isGuessSuccessfull = true;
                }//end if
            }//end for

            for (int k =0; k < hangmanScores.length; k++){
                txtareaWord.setText((hangmanScores[k]));***

1 个答案:

答案 0 :(得分:1)

基本上,每次要向有问题的setText添加新字符时,您都会调用JTextArea,这首先是清除所有现有文本,然后添加新String在这种情况下,这是你输入的最后一件事。

有几种方法可以解决这个问题,但是因为你想首先删除现有的文本然后替换它,最好是建立一个你想要的缓冲区,然后在一个步骤中应用它们......

StringBuilder sb = new StringBuilder(hangmanScores.length);
for (int k = 0; k < hangmanScores.length; k++) {//displays the ______ in the text area
    sb.append(hangmanScores[k]);
    System.out.print(hangmanScores[k]);//testing purposes
}//end for
txtareaWord.setText(sb.toString());

您似乎也已将多个ActionListener附加到您的按钮上,因为每次点击它时,都会计入两次猜测......