【问题标题】:From Console ouput to TextArea in GUI Java从控制台输出到 GUI Java 中的 TextArea
【发布时间】:2018-09-12 13:00:57
【问题描述】:

我是一名真正的 Java 初学者,我正在尝试将控制台输出重定向到我用 Java (Netbeans) 制作的 GUI 的 TextArea。

这是一个更大项目的一部分,但我首先创建了一个将数据输出到控制台的小程序和一个仅读取这一行的 GUI。 有人可以帮我完成这件事吗?我已经尝试了几种包含 append、JFrame 等的解决方案,但仍然没有成功。

提前谢谢你!

在控制台上显示文本的程序是:

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

我使用 TextArea 创建的 GUI:

更新 由于dosenfant的解决方案,我已经发布了我调整的三个类(包括GUI代码),谢谢!但是,我可能仍然做错了什么,因为它还没有工作。 请多多指教!

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类

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                   

}

重定向输出流
导入 java.io.IOException; 导入 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));
    }
 }

【问题讨论】:

  • jTextArea.append("Test program") 不工作?
  • 您的错误在于方法DisplayUI.start():您必须将框架设置为可见,而不是面板。它应该是public void start() { setVisible(true); }
  • 这确实是问题所在!感谢您的帮助

标签: java


【解决方案1】:

如果你想在清除后写入JTextArea,可以使用如下:

jTextArea.setText("Test program");

如果您希望新文本出现在旧文本之后:

jTextArea.append("Test program");

【讨论】:

  • 感谢您的快速回复!我已经尝试过了,但是在运行项目后,GUI 没有打开,显示文本。我是不是做错了什么?
  • 您在哪个类中定义了 GUI?显示的 sn-p 在控制台上只显示 5 行文本。
  • 这确实是我也想知道的事情之一。这些示例都不是让我熟悉 GUI 的源代码和 ConsoleToGUI 类。这当然是我没有成功发送到我的 GUI 的原因。是否有可能看到一些带有包/类结构的源代码来说明如何实现这一点?
  • 查看我的答案的编辑。你会用你的替换我的 GUI 实现。
  • 感谢您的回复。它仍然不起作用。我可能做错了什么,因此,我用当前的代码结构编辑了我的初始注释。
【解决方案2】:

如果您的目标是将所有输出捕获到System.out(您的代码 sn-p 对我的建议),您可能需要执行以下操作:

  1. 创建PrintStream 的子类,在其write 方法中也(或专门)重定向到文本区域。
  2. 将新的PrintStream设置为System.out

请参阅this example 了解 JavaFX 的相同功能(除了它们不转发到 Swing 组件,但在概念上是相同的)。


例子:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多