如何将javax.mail.Session setDebug重定向到jTextArea

时间:2015-11-17 11:05:53

标签: swing javamail

如何将javax.mail.Session setDebug重定向到jTextArea?

ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
Session mailSession = Session.getDefaultInstance(props, null);
logger.info("JAVAMAIL debug mode is ON");
mailSession.setDebug(true);
mailSession.setDebugOut(ps);
logger.info(os);

2 个答案:

答案 0 :(得分:1)

  1. 您可以创建或查找swing hander implementation并将其附加到JavaMail使用的select date_format(my_timestamp, 'EEEE') from ....记录器命名空间。
  2. 您可以使用线程和piped I/O来读取调试输出并将其写入textarea。
  3. 您可以创建一个缓冲的输出流,在

    javax.mail

答案 1 :(得分:1)

您可以使用http://www.codejava.net/java-se/swing/redirect-standard-output-streams-to-jtextarea中描述的优秀CustomOutputStream类:

import java.io.*;
import java.util.Properties;
import javax.mail.Session;
import javax.swing.*;

public class PrintStream2TextArea {
    public static void main(final String[] arguments) {
        new PrintStream2TextArea().launchGui();
    }

    private void launchGui() {
        final JFrame frame = new JFrame("Stack Overflow");
        frame.setBounds(100, 100, 800, 600);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        final JTextArea textArea = new JTextArea(42, 28);
        setupMailSession(new Properties(), textArea);
        frame.getContentPane().add(textArea);
        frame.setVisible(true);
    }

    private void setupMailSession(final Properties props, final JTextArea textArea) {
        PrintStream ps = new PrintStream(new CustomOutputStream(textArea));
        Session mailSession = Session.getDefaultInstance(props, null);
        //logger.info("JAVAMAIL debug mode is ON");
        mailSession.setDebug(true);
        mailSession.setDebugOut(ps);
        //logger.info(os);
    }

    /**
     * This class extends from OutputStream to redirect output to a JTextArea.
     *
     * @author www.codejava.net
     */
    public static class CustomOutputStream extends OutputStream {
        private JTextArea textArea;

        public CustomOutputStream(JTextArea textArea) {
            this.textArea = textArea;
        }

        @Override
        public void write(int b) throws IOException {
            // redirects data to the text area
            textArea.append(String.valueOf((char)b));
            // scrolls the text area to the end of data
            textArea.setCaretPosition(textArea.getDocument().getLength());
        }
    }
}