JTextPane每行追加日志

时间:2015-08-24 09:26:21

标签: java swing log4j awt jtextpane

我实际上是用JTextPane在我的图形应用程序中编写所有log4j日志。它工作没有任何问题,但实际上它不是立即写我的日志(我的意思是它等待生成所有日志,然后在我的应用程序的最后一次写入它们。)

如何立即写下每个新的日志行?

MainLogger

public class MainLogger {

    public static Logger log = Logger.getLogger("Logger");

    private static boolean init = false;

    private MainLogger(){}

    public static void init(Appender appender,Level l){
        if (init != true){
            log.addAppender(appender);
            log.setLevel(l);
        }
        init = true;
    }


    public static void logWarn(final String s){     
        log.warn(s);
    }

    public static void logError(final String s){
        log.error(s);       
    }

    public static void logError(final Throwable ex){
        log.fatal(new String(),ex);
    }

    public static void logTrace(final String s){
        log.trace(s);
    }

}

FlexibleLayout

public class FlexibleLayout extends Layout {

    private String NL = System.getProperty("line.separator");

    @Override
    public void activateOptions() {
        // TODO Auto-generated method stub

    }

    @Override
    public String format(LoggingEvent event) {
        StringBuffer sb = new StringBuffer();
        sb.append(event.getLevel().toString()).append(": ");
//      sb.append("[")
//      .append(event.getLocationInformation().fullInfo)
//      .append("] :");

        sb.append(event.getMessage()).append(NL);
        if (event.getThrowableInformation() != null){
            String[] s = event.getThrowableStrRep();
            for (int i=0;i<s.length;i++){
                sb.append(s[i]).append(NL);
            }           
        }

        return sb.toString();
    }

    @Override
    public boolean ignoresThrowable() {     
        return false;
    }

}

JTextPaneAppender

public class JTextPaneAppender extends AppenderSkeleton {

    private JTextPane _jtextpane = null;

    public Style _styleNormal;
    public Style _styleBold;
    public Style _styleRed; 
    public Style _styleBlue;    

    private Layout _pl = new FlexibleLayout();

    private JTextPaneAppender(){}
    public JTextPaneAppender(JTextPane j){
        super();
        _jtextpane = j;

         StyledDocument doc= _jtextpane.getStyledDocument();

         _styleNormal=doc.addStyle("regular", null);
         StyleConstants.setForeground(_styleNormal, Color.BLACK);

         _styleBlue=doc.addStyle("blue", null);
         StyleConstants.setForeground(_styleBlue, Color.BLUE);

         _styleBold=doc.addStyle("bold", _styleNormal);
         StyleConstants.setBold(_styleBold, true);
         _styleRed=doc.addStyle("red", _styleBold);
         StyleConstants.setForeground(_styleRed, Color.RED);                
    }

    @Override
    protected void append(LoggingEvent event) {         
        String toLog = _pl.format(event);
        if (_jtextpane != null){
            if (event.getLevel().equals(Level.ERROR)) logError(toLog);
            else if (event.getLevel().equals(Level.FATAL)) logFatal(toLog);
            else if (event.getLevel().equals(Level.WARN)) logWarning(toLog);
            else if (event.getLevel().equals(Level.TRACE)) logTrace(toLog);
         }      
    }

    private void logTrace(String s){
        log(s,_styleNormal);
    }

    private void logWarning(String s){
        log(s,_styleBlue);
    }

    private void logFatal(String s){
        logError(s);
    }

    private void logError(String s){
            log(s,_styleRed);           
    }

    private void log(String s, Style style){
        if (s== null) return;
        if (_jtextpane == null) return;
        StyledDocument doc= _jtextpane.getStyledDocument();
        try {
            doc.insertString(doc.getLength(), s, style);
        } catch (BadLocationException e) {} 
    }

    @Override
    public void close() {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean requiresLayout() {       
        return false;
    }



}

TestFrame

public class TestFrame extends JFrame {

    private static final long serialVersionUID = 1L;

    private JPanel jContentPane = null;

    private JScrollPane jScrollPane = null;

    private JTextPane jTextPane = null;

    private JButton jButton = null;

    private JPanel jPanel = null;

    private JButton jButton1 = null;

    private JButton jButton2 = null;

    private JButton jButton3 = null;

    /**
     * This method initializes jScrollPane  
     *  
     * @return javax.swing.JScrollPane  
     */
    private JScrollPane getJScrollPane() {
        if (jScrollPane == null) {
            jScrollPane = new JScrollPane();
            jScrollPane.setMaximumSize(new Dimension(800, 300));
            jScrollPane.setMinimumSize(new Dimension(800, 300));
            jScrollPane.setPreferredSize(new Dimension(800, 300));
            jScrollPane.setBorder(BorderFactory.createTitledBorder(null, "JtextPane Log", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Dialog", Font.BOLD, 12), new Color(51, 51, 51)));
            jScrollPane.setViewportView(getJTextPane());
        }
        return jScrollPane;
    }

    /**
     * This method initializes jTextPane    
     *  
     * @return javax.swing.JTextPane    
     */
    private JTextPane getJTextPane() {
        if (jTextPane == null) {
            jTextPane = new JTextPane();
            jTextPane.setEditable(false);
            jTextPane.addCaretListener(new javax.swing.event.CaretListener() {
                public void caretUpdate(javax.swing.event.CaretEvent e) {
                    String s = getJTextPane().getText();
                    System.out.println(s.length()); // TODO Auto-generated Event stub caretUpdate()
                }
            });
        }
        return jTextPane;
    }

    /**
     * This method initializes jButton  
     *  
     * @return javax.swing.JButton  
     */
    private JButton getJButton() {
        if (jButton == null) {
            jButton = new JButton();
            jButton.setText("AddError");            
            jButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    MainLogger.logError("An Error");

                    }
            });
        }
        return jButton;
    }

    /**
     * This method initializes jPanel   
     *  
     * @return javax.swing.JPanel   
     */
    private JPanel getJPanel() {
        if (jPanel == null) {
            jPanel = new JPanel();
            jPanel.setLayout(new BoxLayout(getJPanel(), BoxLayout.Y_AXIS));
            jPanel.add(getJButton(), null);
            jPanel.add(getJButton1(), null);
            jPanel.add(getJButton2(), null);
            jPanel.add(getJButton3(), null);
        }
        return jPanel;
    }

    /**
     * This method initializes jButton1 
     *  
     * @return javax.swing.JButton  
     */
    private JButton getJButton1() {
        if (jButton1 == null) {
            jButton1 = new JButton();
            jButton1.setText("Add Exception");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    try {
                        throw new Exception("This is a custom exception");
                    } catch (Exception e1) {
                        MainLogger.logError(e1);
                    }
                }
            });
        }
        return jButton1;
    }

    /**
     * This method initializes jButton2 
     *  
     * @return javax.swing.JButton  
     */
    private JButton getJButton2() {
        if (jButton2 == null) {
            jButton2 = new JButton();
            jButton2.setText("Add Warning");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    MainLogger.logWarn("This is a warning!!");
                }
            });
        }
        return jButton2;
    }

    /**
     * This method initializes jButton3 
     *  
     * @return javax.swing.JButton  
     */
    private JButton getJButton3() {
        if (jButton3 == null) {
            jButton3 = new JButton();
            jButton3.setText("Add Trace");
            jButton3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    MainLogger.logTrace("This is a Trace message!");
                }
            });
        }
        return jButton3;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub                      
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                TestFrame thisClass = new TestFrame();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
                MainLogger.init(
                        new JTextPaneAppender(thisClass.getJTextPane()),
                        org.apache.log4j.Level.TRACE);
            }
        });
    }

    /**
     * This is the default constructor
     */
    public TestFrame() {
        super();
        initialize();
    }

    /**
     * This method initializes this
     * 
     * @return void
     */
    private void initialize() {
        this.setSize(800, 600);
        this.setMaximumSize(new Dimension(800, 600));
        this.setMinimumSize(new Dimension(800, 600));
        this.setPreferredSize(new Dimension(800, 600));
        this.setContentPane(getJContentPane());
        this.setTitle("JFrame");
    }

    /**
     * This method initializes jContentPane
     * 
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(new BorderLayout());
            jContentPane.add(getJScrollPane(), BorderLayout.SOUTH);
            jContentPane.add(getJPanel(), BorderLayout.NORTH);
        }
        return jContentPane;
    }

}  //  @jve:decl-index=0:visual-constraint="10,10"

非常感谢

0 个答案:

没有答案