IDEA
官网下载IDEA社区版
https://www.jetbrains.com/idea/download/#section=windows
设置中文
设置插件界面搜索Chinese插件并安装,然后重启
创建项目
创建Maven项目,设置项目结构SDK
Java doc
https://docs.oracle.com/en/java/javase/index.html
可阅读在线帮助文档
使用Swing
[[IDEA 快速开发 JAVA SWING 教程]]
[[idea 的 Java 窗体可视化工具 Swing UI Designer 的简单使用(一)]]
[[idea 的 Java 窗体可视化工具 Swing UI Designer 的简单使(二)]]
[[swing 的几种布局]]
GUI设计器
使用GUI设计器生成界面
GUI设计器可将GUI生成到二进制类文件或Java源代码
Swing form文件
有时界面不好调整,可直接修改form文件
Swing与多线程
Swing线程之SwingUtilities.invokeLater解释
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
}
});
自定义标题栏
[[java swing 自定义标题栏,缩放窗口,阴影窗口]]
其中DragEvent 拖拽工具类比较有用
外观修改
[[Swing 外观 抗锯齿 字体设置]]
package com.founder.MediaxFileTool.UI;
import javax.swing.*;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.FontUIResource;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
public class UIs {
private static final String FALLBACK_FONT_FAMILY_NAME = Font.SANS_SERIF;
private static final Map<String, String> FONT_FAMILY_NAMES = new HashMap<String, String>();
private static final String[] BEST_FONT_FAMILIES = {
"微软雅黑", "arial", "sans-serif"
};
private static final int BEST_FONT_SIZE = 12; // 12px
static {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontFamilyNames = env.getAvailableFontFamilyNames();
for (String fontFamilyName : fontFamilyNames) {
FONT_FAMILY_NAMES.put(fontFamilyName.toLowerCase(), fontFamilyName);
}
if (!FONT_FAMILY_NAMES.containsKey("serif")) {
FONT_FAMILY_NAMES.put("serif", Font.SERIF);
}
if (!FONT_FAMILY_NAMES.containsKey("sans-serif")) {
FONT_FAMILY_NAMES.put("sans-serif", Font.SANS_SERIF);
}
}
public static void enableAntiAliasing() {
System.setProperty("awt.useSystemAAFontSettings", "on");
System.setProperty("swing.aatext", "true");
}
public static String getLookAndFeel() {
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
return info.getClassName();
}
}
} catch (Exception ignore) {
}
return UIManager.getCrossPlatformLookAndFeelClassName();
}
public static String getFontFamily(String[] fontFamilies) {
for (String fontFamily : fontFamilies) {
fontFamily = fontFamily.toLowerCase();
if (FONT_FAMILY_NAMES.containsKey(fontFamily)) {
return FONT_FAMILY_NAMES.get(fontFamily);
}
}
return FALLBACK_FONT_FAMILY_NAME;
}
public static String[] getBestFontFamilies() {
return BEST_FONT_FAMILIES;
}
public static int getBestFontSize() {
return BEST_FONT_SIZE;
}
public static void setUI() {
enableAntiAliasing();
// set LookAndFeel
try {
//UIManager.setLookAndFeel(getLookAndFeel());
/*UIManager.put("OptionPane.background",Color.WHITE);
UIManager.put("Panel.background", Color.WHITE);
UIManager.put("Panel.foreground", Color.black);
UIManager.put("Button.background", Color.WHITE);
UIManager.put("Button.foreground", Color.black);
UIManager.put("Label.background", Color.WHITE);
UIManager.put("Label.foreground", Color.black);
UIManager.put("Panel.background", Color.WHITE);
UIManager.put("Panel.foreground", Color.black);*/
} catch (Exception ignore) {
}
// set DefaultFont
String bestFontFamily = getFontFamily(getBestFontFamilies());
for (Map.Entry<Object, Object> entry : UIManager.getDefaults().entrySet()) {
if (entry.getValue() instanceof FontUIResource) {
FontUIResource fontUIRes = (FontUIResource) entry.getValue();
entry.setValue(new FontUIResource(
bestFontFamily,
fontUIRes.getStyle(),
getBestFontSize() > fontUIRes.getSize() ?
getBestFontSize() : fontUIRes.getSize()
));
}
//默认主题可使用以下代码
if (entry.getValue() instanceof ColorUIResource) {
ColorUIResource fontUIRes = (ColorUIResource) entry.getValue();
if (entry.getKey().toString().endsWith("background")){
entry.setValue(new ColorUIResource(Color.WHITE));
}
if (entry.getKey().toString().endsWith("foreground")){
entry.setValue(new ColorUIResource(Color.black));
}
}
}
}
}
更改JOption的背景颜色以及button的字体
https://blog.csdn.net/Mr_Pang/article/details/47339373
具体的可以更改的东西,请看点击打开链接
UIManager.setLookAndFeel(getLookAndFeel());
UIManager.put("OptionPane.background",Color.WHITE);
UIManager.put("Panel.background", Color.WHITE);
UIManager.put("Panel.foreground", Color.black);
UIManager.put("Button.background", Color.WHITE);
UIManager.put("Button.foreground", Color.black);
控件设置焦点
//先setVisible(true);显示窗口
//passwordField1.dispatchEvent(new FocusEvent(passwordField1,FocusEvent.FOCUS_GAINED,true));
passwordField1.requestFocusInWindow();
passwordField1.requestFocus();
passwordField1.enableInputMethods(true);//开启输入法支持
//放到windowOpened中
frame.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
passwordField1.requestFocusInWindow();
passwordField1.enableInputMethods(true);
}
});
JTextField内容修改
class TextDocumentListener implements DocumentListener{
@Override
public void insertUpdate(DocumentEvent e) {
GetCaptcha();
}
@Override
public void removeUpdate(DocumentEvent e) {
GetCaptcha();
}
@Override
public void changedUpdate(DocumentEvent e) {
}
}
DocumentListener documentListener = new TextDocumentListener();
textFieldServer.getDocument().addDocumentListener(documentListener);
程序配置文件
package com.founder.MediaxFileTool;
import java.io.*;
import java.util.Properties;
public class ConfigManager {
private static ConfigManager configManager;
private static Properties properties;
private static String strConfigFile;
public ConfigManager() {
String mediaxFileToolpath = System.getProperty("user.home") + File.separator + ".xx";
File mediaxFileToolDir = new File(mediaxFileToolpath);
if (!mediaxFileToolDir.exists()) {
mediaxFileToolDir.mkdirs();
}
strConfigFile = mediaxFileToolpath + File.separator + "xx.xml";
File configFile = new File(strConfigFile);
properties = new Properties();
if (configFile.exists()){
try {
InputStream input=new BufferedInputStream(new FileInputStream(strConfigFile));
properties.loadFromXML(input);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static ConfigManager getInstance(){
if(configManager==null){
configManager = new ConfigManager();
}
return configManager;
}
public String getString(String key){
return properties.getProperty(key);
}
public void setString(String key,String value){
properties.setProperty(key,value);
}
public void save() {
try {
OutputStream output = new FileOutputStream(strConfigFile);
properties.storeToXML(output,"xx配置","utf-8");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Meavn
搜索库:https://search.maven.org/
HTTP库
HttpURLConnection与HttpClient,OkHttp
HttpClient
https://hc.apache.org/httpcomponents-client-5.1.x/index.html
https://hc.apache.org/httpcomponents-client-5.1.x/current/httpclient5/apidocs/
异步
package com.founder.MediaxFileTool.Http;
import com.founder.MediaxFileTool.UI.ConfigManager;
import com.founder.MediaxFileTool.UI.StartProgram;
import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
import org.apache.hc.client5.http.async.methods.SimpleRequestProducer;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.reactor.IOReactorConfig;
import org.apache.hc.core5.util.TimeValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class AsyncHttpClientUtil {
private static CloseableHttpAsyncClient closeableHttpAsyncClient = null;
private static final Logger logger = LoggerFactory.getLogger(AsyncHttpClientUtil.class);
public synchronized static CloseableHttpAsyncClient getHttpAsyncClient() {
if (closeableHttpAsyncClient==null){
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(50000, TimeUnit.MILLISECONDS)
.setResponseTimeout(50000,TimeUnit.MILLISECONDS)
.setConnectionRequestTimeout(5000, TimeUnit.MILLISECONDS)
.build();
//配置io线程
IOReactorConfig ioReactorConfig = IOReactorConfig.custom().
setIoThreadCount(Runtime.getRuntime().availableProcessors())
.setSoKeepAlive(true)
.build();
//设置连接池大小
PoolingAsyncClientConnectionManager connManager = new PoolingAsyncClientConnectionManager ();
connManager.setMaxTotal(200);
connManager.setDefaultMaxPerRoute(200);
closeableHttpAsyncClient = HttpAsyncClients.custom().setIOReactorConfig(ioReactorConfig).
setConnectionManager(connManager)
.setDefaultRequestConfig(requestConfig)
.evictExpiredConnections()
.evictIdleConnections(TimeValue.ofMinutes(3))
.build();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
AsyncHttpClientUtil.Shutdown();
}
});
closeableHttpAsyncClient.start();
}
return closeableHttpAsyncClient;
}
public static void Shutdown(){
if (closeableHttpAsyncClient!=null){
try {
closeableHttpAsyncClient.close();
} catch (IOException e) {
logger.error("HttpClient close exception", e);
}
}
}
//Get请求也可以有body
public static void DoHttpGet(String uri,/*String strBodyText,*/FutureCallback<SimpleHttpResponse> callback) {
SimpleHttpRequest request = SimpleRequestBuilder.get( uri)
.build();
//request.setBody(strBodyText, ContentType.APPLICATION_JSON);
// HttpGet httpGet = new HttpGet("http://apis-mediax.devx.fzyun.io/mediax-system/e5/login/captcha");
// HttpEntity httpEntity = new StringEntity("{\n" +
// " \"user\": \"test\", \n" +
// " \"password\": \"Founder123\"\n" +
// "}", ContentType.APPLICATION_JSON);
// httpGet.setEntity(httpEntity);
//SimpleRequestProducer.create(request)
Future<SimpleHttpResponse> future = getHttpAsyncClient().execute(request, callback);
//SimpleHttpRequest
}
}
日志库
https://blog.csdn.net/goodjava2007/article/details/125195211
使用slf4j桥接其他日志库 (Log4j)
- 只定义接口没有具体实现的接口标准框架,如:Commons Logging、SLF4J、JCL(Jakarta Commons Logging)、jboss-logging;
- 有具体实现的日志实现方案,如:Log4j,Log4j2,Logback,Java Util Logging(Jul)、slf4j-simple、slf4j-nop。
- Logback、slf4j-simple、slf4j-nop直接原生实现了slf4j的接口;
- Log4j、Log4j2、Java Util Logging(Jul)没有直接实现slf4j接口,所以需要对应的适配类将SLF4J接口和具体实现类进行绑定。
使用SLF4J
Meavn中pom.xml配置
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.36</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.36</version>
</dependency>
resources添加文件log4j.properties
log4j.rootLogger=INFO, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH:mm:ss}][%C{1}:%L] - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=log.log
log4j.appender.R.MaxFileSize=512KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH:mm:ss}][%C{1}:%L] - %m%n
代码使用
private static final Logger logger = LoggerFactory.getLogger(xx.class);
logger.info("启动");
Json库
FastJson
序列化
TestClass testClass;
Object obj = JSONObject.toJSON(testClass);
try {
OutputStream output = new FileOutputStream(JsonFile;
JSON.writeJSONString(output, obj);
output.close();
} catch (IOException e) {
}
反序列化
File file;
InputStream input = new BufferedInputStream(new FileInputStream(file));
TestClass testClass = JSON.parseObject(input, TestClass.class);
input.close();
导出jar包
[[Idea导出可运行jar包及运行方法]]
其中设置META-INF/MANIFEST.MF,选择项目所在根目录,默认目录不对,会造成jar不可启动
运行jar
使用命令
start javaw -jar xx.jar -Dfile.encoding=GB18030
#或
start java -jar xx.jar -Dfile.encoding=GB18030