简体   繁体   English

从控制台输出到GUI Java中的TextArea

[英]From Console ouput to TextArea in GUI Java

I'm a real beginner in Java and am trying to redirect the console output to a TextArea of a GUI I made in Java (Netbeans). 我是Java的真正初学者,正在尝试将控制台输出重定向到我用Java(Netbeans)制作的GUI的TextArea。

This is part of a bigger project but I first created a small program which outputs data to the console and a GUI which only reads this one line. 这是一个较大项目的一部分,但是我首先创建了一个小程序,该程序将数据输出到控制台和一个GUI,该GUI仅读取这一行。 Could somebody help me to get this done? 有人可以帮我完成这项工作吗? I've tried already several solutions containing append, JFrame etc. still without success. 我已经尝试了几种包含append,JFrame等的解决方案,但仍然没有成功。

Thank you in advance! 先感谢您!

The program to display text on the console is: 在控制台上显示文本的程序是:

public class ConsoleToGUI {

    public void run(){
        for (int i = 0; i < 5; i++){
            System.out.println("Test program");
        }
    }

    public static void main(String[] args){
        ConsoleToGUI ctg = new ConsoleToGUI();
        ctg.run();
    }

The GUI I've created with a TextArea : 我使用TextArea创建的GUI:
在此处输入图片说明
Update Underneath I've posted the three classes (including the GUI code) which I've adjusted thanks to dosenfant's solution, thank you! 在下面的更新中,我已经发布了三个剂量(包括GUI代码),这三个剂量是由于剂量剂解决方案而调整的,谢谢! However, I might still be doing something wrong since it is not working as of yet. 但是,我可能仍在做一些错误的事情,因为它到目前为止还无法正常工作。 Please your advise! 请您指教!

import java.io.PrintStream;
import javax.swing.*;

public class ConsoleToGUI {

public ConsoleToGUI() {
    DisplayUI gui = new DisplayUI();
    System.setOut(new PrintStream(new RedirectingOutputStream(gui), true));
    gui.start();
}


public void run(){

    for (int i = 0; i < 5; i++){
    JTextArea jTextArea1 = new JTextArea();
    System.out.println("Test program");
    }
}

public static void main(String[] args){
    ConsoleToGUI ctg = new ConsoleToGUI();
    ctg.run();
 }
}  

GUI Class GUI类

public class DisplayUI extends javax.swing.JFrame {

/**
 * Creates new form DislapUI
 */
public DisplayUI() {
    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() {

    jPanel1 = new javax.swing.JPanel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, 
    "Console Output: ", 
    javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, 
    javax.swing.border.TitledBorder.DEFAULT_POSITION, new 
    java.awt.Font("Tahoma", 1, 11), new java.awt.Color(51, 153, 255))); // 
    NOI18N

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

    javax.swing.GroupLayout jPanel1Layout = new 
    javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 348, Short.MAX_VALUE)
            .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(15, Short.MAX_VALUE))
    );

    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()
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

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

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(DisplayUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(DisplayUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(DisplayUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(DisplayUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new DisplayUI().setVisible(true);
        }
    });
}

public void start() {
    jPanel1.setVisible(true);
}

public void appendText(String text) {
    jTextArea1.append(text);
}

// Variables declaration - do not modify                     
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration                   

} }

RedirectingOutputStream RedirectingOutputStream
import java.io.IOException; 导入java.io.IOException; import java.io.OutputStream; 导入java.io.OutputStream;

public class RedirectingOutputStream extends OutputStream {

    private DisplayUI gui;

    public RedirectingOutputStream(DisplayUI gui) {
        this.gui = gui;
    }

    @Override
    public void write(int b) throws IOException {
        gui.appendText(String.valueOf((char) b));
    }
 }

If you want to write in the JTextArea after clearing it, you can use the following: 如果要在清除JTextArea后写入它,可以使用以下命令:

jTextArea.setText("Test program");

And if you want the new text to appear after an older text: 并且如果您希望新文本出现在旧文本之后:

jTextArea.append("Test program");

If your goal is to catch all output to System.out (what your code snippet suggests to me) you might want to do the following: 如果您的目标是捕获所有到System.out输出(您的代码段对我的建议),则可能需要执行以下操作:

  1. Create a subclass of PrintStream which in its write methods also (or exclusively) redirects to the text area. 创建一个PrintStream的子类,该子类在其write方法中也(或仅)重定向到文本区域。
  2. Set the new PrintStream as System.out 将新的PrintStream设置为System.out

See this example for JavaFX which does the same (except that they are not forwarding to a Swing component, but conceptually it's the same). 请参阅此示例以了解JavaFX的用法,该操作相同(只是它们没有转发到Swing组件,但从概念上讲是相同的)。


Example: 例:

package example;

import java.io.PrintStream;

public class ConsoleToGUI {

    public ConsoleToGUI() {
        GUI gui = new GUI();
        System.setOut(new PrintStream(new RedirectingOutputStream(gui), true));
        gui.start();
    }

    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Test program");
        }
    }

    public static void main(String[] args) {
        ConsoleToGUI ctg = new ConsoleToGUI();
        ctg.run();
    }
}

package example;

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class GUI {

    private JTextArea textArea;
    private JFrame frame;

    public GUI() {
        frame = new JFrame("Example");
        frame.setBounds(0, 0, 600, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        textArea = new JTextArea();
        frame.getContentPane().add(textArea, BorderLayout.CENTER);
    }

    public void start() {
        frame.setVisible(true);
    }

    public void appendText(String text) {
        textArea.append(text);
    }
}

package example;

import java.io.IOException;
import java.io.OutputStream;

public class RedirectingOutputStream extends OutputStream {

    private GUI gui;

    public RedirectingOutputStream(GUI gui) {
        this.gui = gui;
    }

    @Override
    public void write(int b) throws IOException {
        gui.appendText(String.valueOf((char) b));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM