简体   繁体   English

在java中与Swing GUI一起打开一个控制台

[英]Open a console alongside a Swing GUI in java

I am building an application with a Swing GUI. 我正在使用Swing GUI构建应用程序。 If you would would open this program from the command line, Some text will print (info and error messages). 如果您要从命令行打开此程序,将打印一些文本(信息和错误消息)。 The program is just a normal executable jar file, but for the people who want to see a console I want an option to open a console from the Swing GUI, which displays all these messages, outputted by System.out.print() . 该程序只是一个普通的可执行jar文件,但对于想要查看控制台的人我想要一个 Swing GUI打开控制台的选项,该控件显示System.out.print()输出的所有这些消息。 I have seen several applications which have such a function, but I don't know how to do this. 我见过几个具有这种功能的应用程序,但我不知道该怎么做。

The basics are explained at https://blogs.oracle.com/nickstephen/entry/java_redirecting_system_out_and . 基础知识在https://blogs.oracle.com/nickstephen/entry/java_redirecting_system_out_and中解释。 That example uses logging to redirect stdout and stderr. 该示例使用日志记录来重定向stdout和stderr。 A simple approach could be to first define an OutputStream that writes to the "console": 一种简单的方法可能是首先定义一个写入“控制台”的OutputStream:

package outerr;

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

public class PrintOutErrStream extends ByteArrayOutputStream {

final int maxTextAreaSize = 1000;
private JTextArea textArea;
public PrintOutErrStream(JTextArea textArea) {
    this.textArea = textArea;
}

public void flush() throws IOException {
    synchronized(this) {
        super.flush();
        String outputStr = this.toString();
        super.reset();
        if(textArea.getText().length() > maxTextAreaSize) {
            textArea.replaceRange("", 0, 100);
        }
        textArea.append(outputStr);
    }
}
}

Then this is the remaining part of a demo program: 那么这是演示程序的剩余部分:

package outerr;

import java.io.PrintStream;

public class StdOutErr extends javax.swing.JFrame {

/** Creates new form StdOutErr */
public StdOutErr() {
    initComponents();
    PrintOutErrStream poes = new PrintOutErrStream(this.jTextAreaOutErrLog);
    System.setErr(new PrintStream(poes, true));
    System.setOut(new PrintStream(poes, true));
}

/** 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() {
    java.awt.GridBagConstraints gridBagConstraints;

    jButtonStdout = new javax.swing.JButton();
    jButtonStderr = new javax.swing.JButton();
    jPanelOutErrLog = new javax.swing.JPanel();
    jScrollPaneOutErrLog = new javax.swing.JScrollPane();
    jTextAreaOutErrLog = new javax.swing.JTextArea();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(new java.awt.FlowLayout());

    jButtonStdout.setText("stdout");
    jButtonStdout.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButtonStdoutActionPerformed(evt);
        }
    });
    getContentPane().add(jButtonStdout);

    jButtonStderr.setText("stderr");
    jButtonStderr.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButtonStderrActionPerformed(evt);
        }
    });
    getContentPane().add(jButtonStderr);

    jTextAreaOutErrLog.setColumns(20);
    jTextAreaOutErrLog.setRows(5);
    jScrollPaneOutErrLog.setViewportView(jTextAreaOutErrLog);

    javax.swing.GroupLayout jPanelOutErrLogLayout = new javax.swing.GroupLayout(jPanelOutErrLog);
    jPanelOutErrLog.setLayout(jPanelOutErrLogLayout);
    jPanelOutErrLogLayout.setHorizontalGroup(
        jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 835, Short.MAX_VALUE)
        .addGroup(jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPaneOutErrLog, javax.swing.GroupLayout.DEFAULT_SIZE, 835, Short.MAX_VALUE))
    );
    jPanelOutErrLogLayout.setVerticalGroup(
        jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 378, Short.MAX_VALUE)
        .addGroup(jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPaneOutErrLog, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE))
    );

    getContentPane().add(jPanelOutErrLog);

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

private void jButtonStdoutActionPerformed(java.awt.event.ActionEvent evt) {
    System.out.println("message via stdout");
}

private void jButtonStderrActionPerformed(java.awt.event.ActionEvent evt) {
       System.err.println("message via stderr");
}

/**
 * @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(StdOutErr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(StdOutErr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(StdOutErr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(StdOutErr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new StdOutErr().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JButton jButtonStderr;
private javax.swing.JButton jButtonStdout;
private javax.swing.JPanel jPanelOutErrLog;
private javax.swing.JScrollPane jScrollPaneOutErrLog;
private javax.swing.JTextArea jTextAreaOutErrLog;
// End of variables declaration
}

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

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