指点成金-最美分享吧

登录

IDEA使用swing创建应用程序

佚名 举报

篇首语:本文由小编为大家整理,主要介绍了IDEA使用swing创建应用程序相关的知识,希望对你有一定的参考价值。

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() @Overridepublic void run() );

Java Swing开发EDT机制

SwingWorker的用法

自定义标题栏

[[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()            

以上是关于IDEA使用swing创建应用程序的主要内容,如果未能解决你的问题,请参考以下文章