Ошибка при перенаправлении вывода в JTextArea в Java - PullRequest
0 голосов
/ 25 апреля 2020

Я впервые создаю GUI, так как вторая часть моего GUi переводит мою программу CUI в программу GUI. Теперь я следовал этому руководству, чтобы все это сделать, но оно не работает. Внутри моего GUI класса я установил JTextArea на publi c stati c, так как мне нужен доступ из других классов main.

Ниже приведен основной класс:

public class TrainingProgramme {

static PrintStream printStream = new PrintStream(new GUITextOutputStream(TrainingProgrammeGUI.jTextArea1));

 public static void main(String[] args) {

    TrainingProgrammeGUI gui = new TrainingProgrammeGUI();
    gui.setVisible(true);
    System.setOut(printStream);
    System.setErr(printStream);

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

}

GUI класс:

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 viljo
 */

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;  

/**
 * 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();

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

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, 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()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(261, 261, 261)
                    .addComponent(jLabel1))
                .addGroup(layout.createSequentialGroup()
                    .addGap(94, 94, 94)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 456, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(layout.createSequentialGroup()
                    .addGap(170, 170, 170)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(33, 33, 33)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(33, 33, 33)
                    .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(175, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel1)
            .addGap(70, 70, 70)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 60, Short.MAX_VALUE)
            .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, 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(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel2))
            .addGap(20, 20, 20))
    );

    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("sdsdsdsdsa");
    System.setOut(printStream);
    System.setErr(printStream);

    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

    boolean userFinished = false;
    gameCharacter.getHotelRoom().setPlayerHere(true);
    do {  // Checks which room player is in then reads instructions for room. Loop finishes when player wants to chooses suspect
        if (gameCharacter.getHotelKitchen().isPlayerHere()) {
        if ("HotelRoom".equals((gameCharacter.getHotelKitchen().instructions(teacher)))) {
            System.out.println("\nRoom chosen!\n");
            gameCharacter.getHotelKitchen().setPlayerHere(false); // Takes player out of current room
            gameCharacter.getHotelRoom().setPlayerHere(true);     // Puts players into chosen room
            }
        } else {
            if ("Choose".equals((gameCharacter.getHotelRoom().instructions(teacher)))) {    
                stopTimer = System.nanoTime();
                Player.timeTaken = (stopTimer - startTimer) / 10000000; //time taken to finish inspecting items (in seconds)
                teacher.chooseWhoDidIt(gameCharacter);
                finishedProgram = 1; //Stop the curret loop
                userFinished = true; //Stop the main menu loop
            } else {
                System.out.println("\nKitchen chosen!\n");
                gameCharacter.getHotelRoom().setPlayerHere(false);// Takes player out of current room
                gameCharacter.getHotelKitchen().setPlayerHere(true);// Puts players into chosen room
            }
        }
    } while (userFinished == false);
}                                        

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    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");
}                                        

// Variables declaration - do not modify                     
private javax.swing.Box.Filler filler1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
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                   

}

Когда я запускаю этот код, я получаю ошибка

Исключение: java .lang.NullPointerException, выброшенное из UncaughtExceptionHandler в потоке "main"

Это происходит только после закрытия всплывающего окна GUI ,

Примечание: я не могу редактировать initComponents () напрямую, так как я создал GUI с использованием дизайна NetBeans. Я все еще могу щелкнуть правой кнопкой мыши по каждому элементу и настроить код.

Вся помощь приветствуется!

Редактировать: Обновлен GUI класс, и теперь я не могу заставить работать действия, выполняемые методами. Если вы нажмете на начало игры, то должен был быть вызван jButton1ActionPerformed (что он и делает), но после изменения выходного потока он ничего не делает. Он будет выполнять только эту строку:

System.out.println("sdsdsdsdsa");

, но после этого ничего не происходит, следующие две строки:

System.setOut(printStream); 
System.setErr(printStream);

Редактировать две: похоже, что он застрял в методе jButton1ActionPerformed , Я попытался добавить еще одну печать после запуска методов System.set, и она не печатает. Затем я попытался нажать кнопку «Выход», которая имеет:

System.out.print("\nThank you for using our training programme!");
System.exit(0);

Но программа не закрывается.

...