码农之家 - Swing
type: channel
link: http://blog.liyx.fun/index.php/tag/Swing/
items: Java Swing 点击事件异步执行
items: log4j2自定义Appender 实现输出日志到 JTextArea控件

Java Swing 点击事件异步执行
type: item
date: 2022-03-13T15:09:27+08:00
description: 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(); } });

log4j2自定义Appender 实现输出日志到 JTextArea控件
type: item
date: 2022-03-13T13:24:41+08:00
description: 一、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 MyCustomAppen…