Как проверить ввод пользователя без l oop in java swing gui - PullRequest
0 голосов
/ 07 мая 2020

В моем предыдущем вопросе я спросил, почему мой GUI ничего не делает после того, как я нажал кнопку, и обнаруженная проблема заключалась в том, что у меня было бесконечное l oop, которое закончилось только после того, как пользователь ввел правильное значение. Но после того, как выяснилось, что у вас не может быть такого типа бесконечных циклов в GUI, как тогда проверить ввод пользователя?

В настоящее время я изменил его на a для l oop, и условие «break» состоит в том, что переменная finished равна true. Он становится равным истине, когда входит в один из операторов if. Однако это все еще кажется бесконечным l oop.

Кажется, я не вижу ничего в Интернете о том, как выполнять циклы в GUI, как показано выше.

GUI класс с Main:

package javaapplication2;

import java.awt.event.ActionEvent;
import java.io.PrintStream;
import java.util.Scanner;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author 
 */

public class TrainingProgrammeGUI extends javax.swing.JFrame {

static PrintStream printStream = new PrintStream(new GUITextOutputStream(TrainingProgrammeGUI.jTextArea1));
double startTimer = System.nanoTime();
double stopTimer = 0;
Scanner scan = new Scanner(System.in);
Player gameCharacter = null;
Teacher teacher = null;
int finishedProgram = 0;   
int userChoice = -1;  
boolean inRoom = true;

/**
 * Creates new form TrainingProgrammeGUI
 */
public TrainingProgrammeGUI() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767));
    jLabel1 = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jTextField1 = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    jButton1 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jLabel3 = new javax.swing.JLabel();
    jButton4 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton5 = new javax.swing.JButton();
    jButton6 = new javax.swing.JButton();
    jButton7 = new javax.swing.JButton();
    jButton9 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
    jLabel1.setText("CIA Training Programme");

    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);

    jTextField1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextField1ActionPerformed(evt);
        }
    });

    jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
    jLabel2.setText("Game: ");

    jButton1.setText("Start Game");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jButton3.setText("What is this game?");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });

    jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
    jLabel3.setText("Type Here: ");

    jButton4.setText("Exit");
    jButton4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton4ActionPerformed(evt);
        }
    });

    jButton2.setText("Inspect 2");

    jButton5.setText("Inspect 1");

    jButton6.setText("Inspect 3");

    jButton7.setText("Choose Suspect");

    jButton9.setText("Enter Room");
    jButton9.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton9ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
                    .addComponent(jLabel3)
                    .addGap(515, 515, 515))
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(159, 159, 159))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(166, 166, 166)
                    .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jButton7)
                                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGap(0, 0, Short.MAX_VALUE)))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 487, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(10, 10, 10))))
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jLabel1)
            .addGap(232, 232, 232))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(32, 32, 32)
                    .addComponent(jLabel1)
                    .addGap(60, 60, 60)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(27, 27, 27)
                    .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 96, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel2)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap())
    );

    pack();
}// </editor-fold>                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
     TrainingProgrammeGUI programme = new TrainingProgrammeGUI();
     programme.setVisible(true);
}

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
}                                           

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                            
    System.out.print("\nThank you for using our training programme!");
    System.exit(0);
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    System.out.println("1/2");
    System.setOut(printStream);
    System.setErr(printStream);
    System.out.println("2/2");


    System.out.println("==================================\n"+
                       "* WELCOME TO CATCH ME IF YOU CAN *\n"+
                       "==================================\n");                                     

    userChoice = TrainingProgramme.checkInputWithPhrase("1.) Start Game\n2.) What is this game?\n3.) Quit", 1, 3);
    teacher = new Teacher("John Doe", "Teacher");
    gameCharacter = teacher.introductionLines(); // teacher reads a few lines and asks questions then returns Player class
}                                        

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    System.setOut(printStream);
    System.setErr(printStream);

    System.out.println("\n+===========================================================+");
    System.out.println("|This game was created to help train our new junior recruits|");
    System.out.println("+===========================================================+\n\n");

    System.out.println("Objective: Gather evidence by looking for clues\n"+ 
                       "and once you are done go back to the room to guess \n"+
                       "which suspect did it. Suspects are provided once you have\n"+ 
                       "went back to the room and decided to guess who did the crime!\n");
}                                        

private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {

}                                        

// Variables declaration - do not modify                     
private javax.swing.Box.Filler filler1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton9;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
// End of variables declaration                   
}

GUITextOutputStream:

/*
 * A class that redirects output to GUI
 */
package javaapplication2;

import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JTextArea;

/**
 *
 * @author 
 */

public class GUITextOutputStream extends OutputStream {

private JTextArea textArea;

public GUITextOutputStream(JTextArea textArea) {
    setTextArea(textArea);
}

/**
 * @return the textArea
 */
public JTextArea getTextArea() {
    return textArea;
}

/**
 * @param textArea the textArea to set
 */
public void setTextArea(JTextArea textArea) {
    this.textArea = textArea;
}

@Override
public void write(int i) throws IOException {
    textArea.append(String.valueOf((char) i)); //Redirects text to the GUI text area;
    textArea.setCaretPosition(textArea.getDocument().getLength());
}
}

Класс игрока:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication2;

import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author 
 */
public class Player {

    private String name;

    /**
     *
     * @param name
     * @param cluesLeft
     */
    public Player(String name) {
        this.setName(name);
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }   
}

Класс учителя:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication2;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

/**
 *
 * @author 
 */
public class Teacher extends NPC {


    Scanner scan = new Scanner(System.in);
    private HashMap<String, String> items = new HashMap<>(); //Key is item name and value is item clue 
    private List<String> gameDialogue; // Holds all text information for chooseWhoDidIt() method

    public Teacher(String name, String role) {
        super(name, role);
        BufferedReader reader = null;

        try {
            gameDialogue = Files.readAllLines(Paths.get("GameDialogue.txt"));
        } catch(Exception e) {
            System.out.println("File not found, exact error: "+ e);
        }

        try { 
            reader = new BufferedReader(new FileReader("ItemInspection.txt"));
            String line;
            while ((line = reader.readLine()) != null) { //This reads in the item (as the key) and the clue (as the value) from "ItemInspection.exe"
               String key = line.substring(0, line.indexOf(' '));
               String value = line.substring(line.indexOf(' ') + 1);

               items.put(key, value);
            }
        } catch (IOException e) {
            System.out.println("File not found, exception: "+ e);
        } 
    }

      /**
     * @return the suspectInfo
     */
    public List<String> getGameDialogue() {
        return gameDialogue;
    }

    /**
     * @param suspectInfo the suspectInfo to set
     */
    public void setGameDialogue(List<String> suspectInfo) {
        this.gameDialogue = suspectInfo;
    }

     /**
     * @return the items
     */
    public HashMap<String, String> getItems() {
        return items;
    }

    /**
     * @param items the items to set
     */
    public void setItems(HashMap<String, String> items) {
        this.items = items;
    }

    /**
     * prints out introduction and welcome lines as well as asking player for player name 
     * then creates and returns a Player object 
     * @return Player
     */
    public Player introductionLines() {
        Player gameCharacter;

        String characterName = "";

        System.out.println(TrainingProgramme.obtainGameDialogue(43, 44, null, this.getGameDialogue()));
        pause("long");
        System.out.println(TrainingProgramme.obtainGameDialogue(45, 45, null, this.getGameDialogue()));

        characterName = scan.nextLine();
        if ("".equalsIgnoreCase(characterName)) {
            characterName = characterName + "I can not choose";
        }
        gameCharacter = new Player(characterName, 2);

        System.out.println(TrainingProgramme.obtainGameDialogue(46, 46, null, this.getGameDialogue()) + " " + gameCharacter.getName());
        pause("short");
        System.out.println(TrainingProgramme.obtainGameDialogue(47, 47, null, this.getGameDialogue()));
        pause("short");
        System.out.println(TrainingProgramme.obtainGameDialogue(48, 52, null, this.getGameDialogue()));
        pause("kindoflong");
        System.out.println();

        return gameCharacter;
    }
}

NP C:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication2;

import java.util.List;

/**
 *
 * @author 
 */
public class NPC {

    private String name;
    private String role;

    /**
     *
     * @param name
     * @param role
     */
    public NPC(String name, String role) {
        this.setName(name);
        this.setRole(role);
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the role
     */
    public String getRole() {
        return role;
    }

    /**
     * @param role the role to set
     */
    public void setRole(String role) {
        this.role = role;
    }

    /**
     * Pauses all code for a certain length to allow player to read
     * @param length
     */
    public void pause(String length) { //Calling pause results in Thread.sleep(time) and time being bassed of the string provided

        if ("veryshort".equalsIgnoreCase(length)) {
            try {
                Thread.sleep(1500);
            } catch (Exception e) {
                System.out.println(e);
            } 
        } else if("short".equalsIgnoreCase(length)) {
            try {
                Thread.sleep(3000);
            } catch (Exception e) {
                System.out.println(e);
            } 
        } else if("kindoflong".equalsIgnoreCase(length)) {
            try {
                Thread.sleep(10000);
            } catch (Exception e) {
                System.out.println(e);
            } 
        } else if ("verylong".equalsIgnoreCase(length)) {
            try {
                Thread.sleep(22000);
            } catch (Exception e) {
                System.out.println(e);
            }
        } else {
            try {
                Thread.sleep(4000);
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }

}

TrainingProgramme:

package javaapplication2;

import java.io.PrintStream;
import java.util.List;
import java.util.Scanner;

/**
 *
 * @author 
 */
public class TrainingProgramme {

    /**
     *
     */
    static Scanner scan = new Scanner(System.in); 
    static PrintStream printStream = new PrintStream(new GUITextOutputStream(TrainingProgrammeGUI.jTextArea1));

    /**
     * Checks (and makes sure) that users input is valid whilst also printing supplied String each loop
     * @param phrase
     * @return int
     */
    public static int checkInputWithPhrase(String phrase, int firstOption, int lastOption) {//Make sure input given is valid 

        boolean correctInput = false;
        int userChoice = 0;
        for (boolean finished = false; finished != true;) { //Makes sure user input correct value
            boolean exception = false;               // checks if an exception was caught in the current loop
            try {                                       
                System.out.println(phrase);
                userChoice = scan.nextInt();
                } catch (Exception e) {
                    System.out.println("\nPlease input a number only!\n");
                    System.out.println("\nError code for developer: " + e + "\n");
                    exception = true;
                }
                if (exception == false) {
                    if (userChoice >= firstOption && userChoice <= lastOption) {
                        finished = true;
                        return userChoice;
                    } else {
                        System.out.println("\nPlease input a number within the above range!\n");
                    }
                }
                if (exception == true) { // clear buffer is user has previously inputed wrong value
                        scan.next();
                }
        }
        return 0;
    } 

        /**
     * method reads, saves and returns data from a list (which  is comprised of all text from "GameDialogue.txt")
     * @param start
     * @param end
     * @param doesItContain
     * @return String
     */
    public static String obtainGameDialogue (int start, int end, String doesItContain, List<String> dialogue) { 
        String finalString = "";
        boolean firstLoop = true;

        for (int x = start; x <= end; x++) {
            if (start == end && firstLoop) { //If only one line will be read 
                finalString = finalString + dialogue.get(x);
            } else {
                if (doesItContain != null && doesItContain.equalsIgnoreCase(dialogue.get(x))) { //if doesItContain has a String, which matches a string in the list ,(and not null) then the loop will add two new lines at the end of that String (instead of one)
                finalString = finalString + dialogue.get(x);
                finalString = finalString + "\n\n"; //creates a new paragraph by making a gap
                } else {
                        if (x != end) { 
                            finalString = finalString + dialogue.get(x);
                            finalString = finalString + "\n"; 
                        } else { // does not add new line if x is equal to the last line (end) 
                            finalString = finalString + dialogue.get(x);
                        }
                } 
            }
        }
        finalString = "\n" + finalString;
        return finalString;
    }

}

Извините, если я пропустил какой-то код, просто прокомментируйте ниже, если я это сделал, но я считаю, что это все. Я сделал его настолько минимальным, насколько это возможно, но многие мои классы имеют методы, которые связаны с другими классами.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...