如何清除JTextField并准备好立即输入而无需单击或其他操作?

问题描述 投票:0回答:1

我在下面发布了我的完整代码,所以你们可以对我想要的东西有充分的理解。单击“发送”时,文本字段将清除但尚未准备好输入。我必须点击输入。我希望它立即为输入做好准备,textfield.setText(“”)将无效。有任何想法吗?

package javaapplication2;

import java.util.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.io.*;
import javax.swing.*;//class to use to create GUI's
import javax.swing.border.Border;
import javax.swing.plaf.FontUIResource;

/**
 *
 * @author Jordan Anthony Hangman with dictionary
 */

public class JavaApplication2 extends JFrame{

static JLabel[] labels = new JLabel[20];//labels for displaying words under 20 characters
static int counter = 0;
static int badguess = 0;//keeps track of wrong guesses
static String wordbank = "   Letter Bank:";
static char[] guesses = new char[26];
static int nguesses = 0;
static int amountc = 0;

public JavaApplication2(){

}

public static void main(String[] args) throws FileNotFoundException, IOException {

    //Loading images to use for hangman game
    ImageIcon hanginit = new ImageIcon("hangmaninit.jpg");
    ImageIcon hang1 = new ImageIcon("hangman1.jpg");
    ImageIcon hang2 = new ImageIcon("hangman2.jpg");
    ImageIcon hang3 = new ImageIcon("hangman3.jpg");
    ImageIcon hang4 = new ImageIcon("hangman4.jpg");
    ImageIcon hang5 = new ImageIcon("hangman5.jpg");
    ImageIcon hang6 = new ImageIcon("hangman6.jpg");

    //initializing array for index values
    int wordcount = 10;
    String[] words1 = new String[wordcount];
    int[] wordssel = new int[10];
    for (int j=0; j<10; j++){
        wordssel[j] = -1;
    }

    //setting instructions
    String Instructions = "To start the game, click on the new game button. You get 6 incorrect guesses for every word. Once you get 6 guesses, the game will end. Click the end game button to go back to the home page. If you want to play again, you can click New Game and you will be able to guess a different word. After every game, a message will appear to tell you how many words you have guesses correctly. When all the words are played, a dialog box will be shown that says Game Over. Exit this box to exit the game.";

    //reading in the words
    int number = 0;
    try(BufferedReader br = new BufferedReader(new FileReader("words.txt")))       
    {
        String line = br.readLine();
        while(line != null){
            words1[number] = line;
            number++;
            line = br.readLine();
        }
    }

    //randomizes words
    boolean flag = false;
    int rand = 0;
    int count = 0;
    int wordcounter = 0;
    while(!flag){
        Random random = new Random();
        rand = random.nextInt(wordcount);
        count = 0;
        for (int o=0; o<wordcount; o++){
            if(wordssel[o] != rand){
                count++;
            }
        }
        if(count == wordcount){
            wordssel[wordcounter] = rand;
            wordcounter++;
        }
        if(wordcounter == wordcount){
            flag = true;
        }
    }
    String[] randwords = new String[10];
    for(int o=0; o<10; o++){
        randwords[wordssel[o]] = words1[o];
    }

    //initializing label
    for(int i=0; i<20; i++){
        labels[i] = new JLabel(" ");
        labels[i].setFont(new Font("Serif", Font.BOLD, 30));
    }

    //initializing guessedchar array
    for(int i=0; i<26; i++){
        guesses[i] = ' ';
    }

    //value for window size
    int xlim = 1200;
    int ylim = 1200;
    int xlim2 = 1600;
    int ylim2 = 1600;
    int xlim3 = 900;
    int ylim3 = 600;

    //value for x and y centers
    int xcent = xlim/2 - 20;
    int ycent = ylim/2;
    int xcent2 = xlim2/2;
    int ycent2 = ylim2/2 - 20;
    int xcent3 = xlim3/2;
    int ycent3 = ylim3/2 - 20;

    //creating frames
    JFrame frame1 = new JFrame("Hangman");//creates a new frame or window
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// I thiunk exits when clicks on red x
    frame1.setSize(xlim, ylim); //size of window in pixels
    JFrame frame2 = new JFrame("Hangman");//creates a new frame or window
    frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// I thiunk exits when clicks on red x
    frame2.setSize(xlim2, ylim2); //size of window in pixels
    JFrame frame3 = new JFrame();
    frame3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame3.setSize(xlim3, ylim3);

    //change font size for label, button, and textfield
    UIManager.put("Button.font", new FontUIResource(new Font("Dialog", Font.BOLD, 24)));
    UIManager.put("Label.font", new FontUIResource(new Font("Dialog", Font.PLAIN, 24)));
    UIManager.put("TextField.font", new FontUIResource(new Font("Dialog", Font.PLAIN, 24)));
    UIManager.put("TextArea.font", new FontUIResource(new Font("Dialog", Font.PLAIN, 24)));

    //creates buttons
    JButton button1 = new JButton("New Game?");
    button1.setBounds(xcent - 90, ycent - 165, 180, 130);//(xstart, ytop, width, height)
    JButton button2 = new JButton("End Game?");
    button2.setBounds(xcent - 90, ycent - 65, 180, 130);//(xstart, ytop, width, height)
    JButton button3 = new JButton("Instructions");
    button3.setBounds(xcent - 120, ycent, 240, 100);
    JButton button4 = new JButton("Main Menu");
    button4.setBounds(xcent - 100, ycent + 100, 200, 100);

    //creating border
    Border border = BorderFactory.createLineBorder(Color.BLACK, 4);

    //creating labels
    JLabel labelresult = new JLabel("");//label for win or losing game
    labelresult.setBounds(400, 400, 400, 40);
    JLabel labelhang = new JLabel();//label for hangman images
    labelhang.setBounds(450, 375, 677, 620);
    JLabel label3 = new JLabel("Hello");
    label3.setBounds(200, 260, 500, 40);
    JLabel label4 = new JLabel("Hello");
    label4.setBounds(440, 1300, 800, 40);
    JLabel label5 = new JLabel("Hello");
    label5.setBounds(590, 1300, 800, 40);
    JLabel label6 = new JLabel("Game Over");
    label6.setBounds(380, 250, 200, 40);
    JLabel lettersw = new JLabel();
    JLabel label7 = new JLabel("How To Play");
    label7.setBounds(500, 50, 200, 40);
    JLabel label8 = new JLabel("Error");
    label8.setBounds(590, 1300, 800, 40);
    label8.setText("You can only enter one letter at a time.");
    JLabel label9 = new JLabel("Error");
    label9.setBounds(674, 1300, 800, 40);
    label9.setText("You must enter a letter");
    JLabel label10 = new JLabel(wordbank);
    label10.setBounds(xcent2 - 200, 220, 400, 40);
    JLabel label11 = new JLabel("You have already entered this letter.");
    label11.setBounds(608, 1300, 800, 40);
    JLabel label12 = new JLabel("You must exit game to guess.");
    label12.setBounds(639, 1300, 800, 40);


    //creating text area and setting properties
    JTextArea texta1 = new JTextArea();
    texta1.setOpaque(false);
    texta1.setLineWrap(true);
    texta1.setWrapStyleWord(true);
    texta1.setBounds(100, 100, 1000, 600);
    texta1.setText(Instructions);


    //adding items to frames
    frame1.add(button1);
    frame1.add(button3);
    frame2.add(button2);
    frame2.add(labelhang);
    frame3.add(label6);
    frame2.add(label4);
    frame2.add(label5);
    frame3.add(label6);
    frame1.add(label7);
    frame1.add(texta1);
    frame1.add(button4);
    frame2.add(label8);
    frame2.add(label9);
    frame2.add(label10);
    frame2.add(label11);
    frame2.add(label12);

    //set item properties
    labelresult.setVisible(false);
    button2.setVisible(false);
    labelhang.setIcon(hanginit);
    label4.setVisible(false);
    label5.setVisible(false);
    label7.setVisible(false);
    texta1.setVisible(false);
    button4.setVisible(false);
    label8.setVisible(false);
    label9.setVisible(false);
    label10.setBorder(border);
    label11.setVisible(false);
    label12.setVisible(false);

    //set frame properties
    frame1.setLayout(null);
    frame1.setVisible(true);//makes the frame visible to the user
    frame3.setLayout(null);

    //When End Game button is pressed
    button2.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e){

            //end of game conditions
            label5.setVisible(false);
            label4.setVisible(false);
            label12.setVisible(false);
            button2.setVisible(false);
            frame2.setVisible(false);
            wordbank = "   Letter Bank:";
            badguess = 0;
            amountc = 0;
            if(counter == wordcount){
                frame3.setVisible(true);//frame after all words gone through
            }
            else{
                labelhang.setIcon(hanginit);
                frame1.setVisible(true);
            }
        }
    });

    //When Instructions button is pressed
    button3.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e){
            button1.setVisible(false);
            button3.setVisible(false);
            label7.setVisible(true);
            texta1.setVisible(true);
            button4.setVisible(true);
        }
    });

    //When Main Menu is pressed
    button4.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e){
            button1.setVisible(true);
            button4.setVisible(false);
            button2.setVisible(true);
            label7.setVisible(false);
            texta1.setVisible(false);
            button3.setVisible(true);
        }
    });

    //When New Game is press
    button1.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e){

            //set item properties
            frame2.setLayout(null);
            frame2.setVisible(true);
            frame1.setVisible(false);
            button2.setVisible(false);
            label8.setVisible(false);
            label9.setVisible(false);
            wordbank = "   Letter Bank:";
            label10.setText(wordbank);

            //initializes labels and word
            for(int i=0; i<20; i++){
                labels[i].setText(" ");
            }
            String currentword = randwords[counter];
            counter++;

            //initializing previos guesses
            for(int i=0; i<26; i++){
                guesses[i] = ' ';
            }
            nguesses = 0;

            //creating panel and panel components always create panels and all components in the same place that they are being added
            JButton send = new JButton("Send");
            JButton clear = new JButton("clear");
            JTextField tf = new JTextField(1);
            JLabel label = new JLabel("Enter Guess");
            JPanel panel = new JPanel();
            panel.add(label);
            panel.add(tf);
            panel.add(send);
            panel.add(clear);
            panel.setBounds(xcent2 - 250, ylim2 - 102, 500, 40);
            frame2.add(panel);

            //placing labels for letters
            int letters = currentword.length();
            int spacing2 = 800-(int)(letters*12.5);
            for (int i=0; i<letters; i++){
                labels[i].setText("_");
                int spacing = 25 * i;
                labels[i].setBounds(spacing2 + spacing, 1100, 25, 40);
                frame2.add(labels[i]);
            }

            //when clear button is pressed
            clear.addActionListener(new ActionListener(){

                @Override
                public void actionPerformed(ActionEvent e){
                    tf.setText("");
                }
            });

            //when send button is pressed
            send.addActionListener(new ActionListener(){

                int amountc1 = 0;//keeps track of correctly guessed amount of words
                int counter2 = 0;//keeps track of amount of correct letter guesses for each word
                int letters2 = 0;

                @Override
                public void actionPerformed(ActionEvent e){

                    //initialize word and user guess
                    String currentword = randwords[counter-1];
                    letters2 = currentword.length();
                    char[] wordcurrent = new char[20];
                    wordcurrent = currentword.toCharArray();
                    String userguess = tf.getText();
                    userguess = userguess.toLowerCase();
                    tf.setText("");

                    //set properties
                    label4.setVisible(false);
                    label5.setVisible(false);
                    label8.setVisible(false);
                    label9.setVisible(false);
                    label11.setVisible(false);

                    //checking guess with word
                    boolean flag2 = false;
                    boolean flag3 = false;

                    //checking if word is already solved and user is entering data
                    System.out.println(badguess);
                    System.out.println(amountc);
                    System.out.println(nguesses);
                    if(nguesses > badguess + amountc){
                        label4.setVisible(false);
                        label5.setVisible(false);
                        label12.setVisible(true);
                        nguesses++;
                        flag2 = true;
                    }
                    else if(userguess.length() > 1){
                        label8.setVisible(true);
                        flag2 = true;
                        nguesses++;
                    }
                    else if(userguess.length() < 1){
                        label9.setVisible(true);
                        flag2 = true;
                        nguesses++;
                    }
                    else{
                        char[] guessuser = userguess.toCharArray();
                        char guessedchar = guessuser[0];
                        int charval = (int)guessedchar;//97-122 lowercase, 65-90 for uppercase

                        //checks for previous guesses
                        for(int t=0; t<=nguesses; t++){
                            if(guessedchar == guesses[t]){
                                flag3 = true;
                                break;
                            }
                        }
                        nguesses++;

                        //checking word against guess
                        for(int i=0; i<letters2; i++){
                            if(!flag3){
                                if(((charval>96 & charval<123))){
                                    guesses[nguesses] = guessedchar;
                                    if(wordcurrent[i] == guessedchar){
                                        labels[i].setText(userguess);
                                        labels[i].setVisible(true);
                                        flag2 = true;
                                        counter2++;
                                        nguesses++;
                                        amountc++;
                                    }
                                }
                                else{
                                    label9.setVisible(true);
                                    flag2 = true;
                                }
                            }
                            else{
                                label11.setVisible(true);
                                flag2 = true;
                            }
                        }
                    }

                    //checks if full word is guessed correctly
                    if(counter2 == letters2){
                        this.amountc1++;
                        nguesses++;
                        button2.setVisible(true);
                        String correctword = "Well done! You have solved " + amountc1 + " out of " + counter;
                        label5.setText(correctword);
                        label5.setVisible(true);
                        counter2 = 0;
                        if(counter == wordcount){
                            label3.setText(correctword);
                        }
                    }

                    //checks for wrong guess and changes hangman picture accordingly
                    if (flag2 == false){
                        badguess++;
                        switch(badguess){
                            case 1:
                                wordbank += " " + userguess;
                                label10.setText(wordbank);
                                labelhang.setIcon(hang1);
                                break;
                            case 2:
                                wordbank += ", " + userguess;
                                label10.setText(wordbank);
                                labelhang.setIcon(hang2);
                                break;
                            case 3: 
                                wordbank += ", " + userguess;
                                label10.setText(wordbank);
                                labelhang.setIcon(hang3);
                                break;
                            case 4: 
                                wordbank += ", " + userguess;
                                label10.setText(wordbank);
                                labelhang.setIcon(hang4);
                                break;
                            case 5:
                                wordbank += ", " + userguess;
                                label10.setText(wordbank);
                                labelhang.setIcon(hang5);
                                break;
                            case 6:
                                nguesses++;
                                wordbank += ", " + userguess;
                                label10.setText(wordbank);
                                labelhang.setIcon(hang6);
                                button2.setVisible(true);
                                String incorrectword = "Sorry, The correct word was " + currentword + " You have solved " + amountc1 + " out of " + counter;
                                label4.setText(incorrectword);
                                label4.setVisible(true);
                                this.counter2 = 0;
                                if(counter == wordcount){
                                    label3.setText(incorrectword);
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    else{
                        nguesses--;
                    }
                }
            });
        }
    });   
}
}
java swing jtextfield
1个回答
0
投票

要在setText("");方法之后聚焦文本字段,您可以使用以下方法,

textFieldName.requestFocus();

要使文本字段居中,您可以使用此代码,

textFieldName.setHorizontalAlignment(JTextField.CENTER);
© www.soinside.com 2019 - 2024. All rights reserved.