btnCreate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { btnCreate.setEnabled(false); new SwingWorker<StringBuilder, String>(){ @Override protected StringBuilder doInBackground() throws Exception { actionCreate(); return null; } @Override protected void process(List<String> chunks) { super.process(chunks); } @Override protected void done() { super.done(); btnCreate.setEnabled(true); } }.execute(); } });
一、Main类定义输出控件，实例化窗口后赋值为JTextArea控件public class Main { public static JTextArea text = null;//输出日志的控件 public static void main(String[] args) { JFrame frame = new JFrame("窗口"); App app = new App(); frame.setContentPane(app.panel1); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); frame.setResizable(false); frame.setLocationRelativeTo(null); Main.text = app.txtConsoleMsg; app.Init(); } } 二、自定义Appenderpackage com.test.util; import com.test.Main; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginAttribute; import org.apache.logging.log4j.core.config.plugins.PluginElement; import org.apache.logging.log4j.core.config.plugins.PluginFactory; import org.apache.logging.log4j.core.layout.PatternLayout; import javax.swing.*; import java.io.Serializable; @Plugin(name = "JTextArea", category = "Core", elementType = "appender", printObject = true) public class JTextAreaAppender extends AbstractAppender { protected JTextAreaAppender(String name, Filter filter, Layout<? extends Serializable> layout, boolean ignoreExceptions) { super(name, filter, layout, ignoreExceptions); } @Override public void append(LogEvent logEvent) { String msg = logEvent.getMessage().getFormattedMessage(); SwingUtilities.invokeLater(new Runnable() { public void run() { if (Main.text != null) { Main.text.append(msg + "\n");//输出日志到窗口控件 } } }); } // 下面这个方法可以接收配置文件中的参数信息 @PluginFactory public static JTextAreaAppender createAppender(@PluginAttribute("name") String name, @PluginElement("Filter") final Filter filter, @PluginElement("Layout") Layout<? extends Serializable> layout, @PluginAttribute("ignoreExceptions") boolean ignoreExceptions) { if (name == null) { LOGGER.error("No name provided for MyCustomAppenderImpl"); return null; } if (layout == null) { layout = PatternLayout.createDefaultLayout(); } return new JTextAreaAppender(name, filter, layout, ignoreExceptions); } } 二、配置log4j2.xml文件<?xml version="1.0" encoding="UTF-8"?> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> <JTextArea name="JTextArea"/> <appender-ref ref="Console"/> <Appender-Ref ref="JTextArea"/>