1. 程式人生 > >Java Swing視覺化介面開發

Java Swing視覺化介面開發

開發文件地址

踩過的坑:

JFrame設定背景色

          jf.setBackground(Color.blue);
          jf.getContentPane().setBackground(Color.red);//獲取JFrame內容的根元件
          jf.getContentPane().setVisible(true);//如果改為true那麼就變成了紅色。
          jf.setVisible(true);
  • 設定JTextField的大小
          JTextField= new JTextField();
	      yTextField.setPreferredSize(new Dimension(50, 10));
  • 元件設定透明色
panel.setBackground(null);// 設定背景透明 
  • BoxLayout佈局管理器的案例參考demo

       https://blog.csdn.net/sjf0115/article/details/7064909 

/**  
 * All rights Reserved, Designed By NARI
 * @Title:  Main.java   
 * @Package qrcodesoft   
 * @Description: TODO(用一句話描述該檔案做什麼)   
 * @author wuyongcheg     
 * @date   2018年12月12日 下午9:20:35   
 * @version V1.0 
 * @Copyright: 2018 www.naritech.cn All rights reserved. 
 */
package qrcodesoft;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.text.Utilities;

import qrcodesoft.utils.Base64Utils;
import qrcodesoft.utils.FileUtils;
import qrcodesoft.utils.JTextFieldHintListener;
import qrcodesoft.utils.QRCodeUtil;
import qrcodesoft.utils.RSAUtils;
import qrcodesoft.utils.StringUtils;

/**
 * @ClassName: Main
 * @Description: TODO(這裡用一句話描述這個類的作用)
 * @author wuyongcheg
 * @date 2018年12月12日
 *
 */
public class Main {
	private static final String PLEASE_INPUT="請輸入....";
	private static final String PATH_INPUT="例如:D:/資料夾名稱";
	public static void main(String[] args) {
		
		// 1. 建立一個頂層容器(視窗)
		JFrame jf = new JFrame("二維碼生成器"); // 建立視窗
		jf.setSize(700, 600); // 設定視窗大小
		jf.setLocationRelativeTo(null); // 把視窗位置設定到螢幕中心
		jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // 當點選視窗的關閉按鈕時退出程式(沒有這一句,程式不會退出)
		GridBagLayout gridBag = new GridBagLayout(); // 佈局管理器
		GridBagConstraints c = null; // 約束

		// 2. 建立中間容器(面板容器)
		JPanel panel = new JPanel(gridBag);

		// 建立文字標籤
		JLabel label01 = new JLabel();
		label01.setText("請輸入編碼");
		label01.setFont(new Font("微軟雅黑", Font.PLAIN, 18)); // 設定字型,null 表示使用預設字型
		label01.setForeground(Color.black);
		// c = new GridBagConstraints();
		Insets insets0 = new Insets(0, 0, 5, 0);
		c = new GridBagConstraints(-1, -1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, insets0,
				5, 5);
		gridBag.addLayoutComponent(label01, c);

		// 建立文字框,指定可見列數為8列,輸入框的長度
		final JTextField textField01 = new JTextField(19);
		textField01.setFont(new Font(null, Font.PLAIN, 18));
		textField01.addFocusListener(new JTextFieldHintListener(PLEASE_INPUT, textField01));
		/*
		 * c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER;
		 * c.fill = GridBagConstraints.BOTH; GridBagConstraints 中的5,5 代表輸入框panding 值
		 */
		Insets insets1 = new Insets(0, 0, 10, 0);
		c = new GridBagConstraints(-1, -1, 0, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, insets1,
				5, 5);
		gridBag.addLayoutComponent(textField01, c);
		
		JButton jdelBtn=new JButton("清 除");
		jdelBtn.setFont(new Font("微軟雅黑", Font.PLAIN, 16));
		jdelBtn.setForeground(Color.blue);
		Insets insets4 = new Insets(0, 0, 10, 0);
		c = new GridBagConstraints(-1, -1, 0, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, insets4,
				0, 0);
		gridBag.addLayoutComponent(jdelBtn, c);
		
		
		jdelBtn.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				textField01.setText("");
				
			}
		});
		
		
		// 建立文字標籤
		JLabel label02 = new JLabel();
		label02.setText("請輸入二維碼儲存路徑");
		label02.setFont(new Font("微軟雅黑", Font.PLAIN, 18)); // 設定字型,null 表示使用預設字型
		label02.setForeground(Color.black);
		// 元件彼此間的間距 Insets 上,左,下,右
		Insets insets = new Insets(0, 0, 5, 0);
		c = new GridBagConstraints(-1, -1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, insets,
				5, 5);

		gridBag.addLayoutComponent(label02, c);

		// 建立文字框,指定可見列數為8列
		final JTextField textField02 = new JTextField(15);
		textField02.addFocusListener(new JTextFieldHintListener(PATH_INPUT, textField02));
		textField02.setFont(new Font("微軟雅黑", Font.PLAIN, 18));
		c = new GridBagConstraints();
		c.gridwidth = GridBagConstraints.REMAINDER;
		c.fill = GridBagConstraints.BOTH;
		gridBag.addLayoutComponent(textField02, c);
		
		
		
		
		jdelBtn.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				textField01.setText("");
				
			}
		});
		
		

		// 建立一個按鈕,點選後獲取文字框中的文字
		JButton btn = new JButton("生成二維碼");
		btn.setFont(new Font("微軟雅黑", Font.PLAIN, 20));
		btn.setForeground(Color.blue);
		
		try {
			btn.setIcon(new ImageIcon(ImageIO.read(Main.class.getClassLoader().getResource("resources/images/inspection_icon.png"))));
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
		// btn.setFont(new Font(null, Font.PLAIN, 20));
		btn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String text1 = textField01.getText().trim();
				String text2 = textField02.getText().trim(); 
				String newText2="";
				if (text2.contains("/")) {
					 newText2 = text2.replace("/","\\");
					 System.out.println("--------------"+newText2);
				}else {
					newText2=text2;
				}
				try {

					if (StringUtils.isBlank2(text1)||text1.equals(PLEASE_INPUT)) {
						JOptionPane.showMessageDialog(null, "編 碼 不 能  為 空 !", "提示", JOptionPane.WARNING_MESSAGE);

						/*
						 * String priviteKey="rsakey/"+RSAUtils.PRIVITE_KEY; String path =
						 * Main.class.getClassLoader().getResource(priviteKey).getPath(); String string
						 * = FileUtils.getString(path);
						 */

					} else if (StringUtils.isBlank2(newText2)||newText2.equals(PATH_INPUT)) {

						/*String publicKey = "rsakey/" + RSAUtils.PUBLIC_KEY;
						String priviteKey = "rsakey/" + RSAUtils.PRIVITE_KEY;
						// String path = Main.class.getClassLoader().getResource(publicKey).getPath();
						String path1 = Main.class.getClassLoader().getResource(priviteKey).getPath();

						// encryption_Privite(FileUtils.getInputStream(path), text1);
						decode_public(FileUtils.getInputStream(path1),
								"SV0CKPf1hTjmnCTVslbEOMiFdJRUTsgICpjISBsIKiHF2nLKLCtgCLPG6kSpeYUEiVch2hp224ybG/tiBVGsWjVtBq/HGENrzNh+Jhwom62u5MvlOudTgE4zeqzD0H6sL5UaB2ZvQa3ARNJh43HkkEzhbepv3qTwyDhQzC7gS6s=");
*/
						JOptionPane.showMessageDialog(null, "存 儲 路 徑 不 能  為 空 !", "提示", JOptionPane.WARNING_MESSAGE);
					} else if (!StringUtils.isLegalPath(newText2)) {
						JOptionPane.showMessageDialog(null, "存 儲 路 徑  不 合 法 !", "提示", JOptionPane.WARNING_MESSAGE);
					} else if (!StringUtils.isBlank2(newText2) && !StringUtils.isDiskExist(newText2)) {

						JOptionPane.showMessageDialog(null, "存 儲 路 徑  不 存 在 !", "提示", JOptionPane.WARNING_MESSAGE);
					} else {
						QRCodeUtil.encode(text1, "", newText2, true);

					}

				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		/*
		 * c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER;
		 * c.fill = GridBagConstraints.BOTH;
		 */
		// Insets 上,左,下,右
		Insets insets3 = new Insets(10, 0, 0, 0);
		c = new GridBagConstraints(-1, -1, 0, 0, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, insets3,
				5, 5);
		gridBag.addLayoutComponent(btn, c);
		panel.add(label01);
		panel.add(textField01);
		panel.add(label02);
		panel.add(textField02);
		panel.add(btn);
		panel.add(jdelBtn);

		// 4. 把 面板容器 作為視窗的內容面板 設定到 視窗
		jf.setContentPane(panel);

		// 5. 顯示視窗,前面建立的資訊都在記憶體中,通過 jf.setVisible(true) 把記憶體中的視窗顯示在螢幕上。
		jf.setVisible(true);
	}

	/**
	 * 公鑰加密
	 * 
	 * @param inPrivate
	 * @param plaintext
	 */
	public static void encryption_Privite(InputStream inPublic, String plaintext) {
		PrivateKey privateKey;
		try {
			PublicKey publicKey = RSAUtils.loadPublicKey(inPublic);
			// 加密
			byte[] encryptByte = RSAUtils.encryptData(plaintext.getBytes(), publicKey);
			// 為了方便觀察吧加密後的資料用base64加密轉一下,要不然看起來是亂碼,所以解密是也是要用Base64先轉換
			String afterencrypt = Base64Utils.encode(encryptByte);
			System.out.println("--------加密後的字串-------" + afterencrypt);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 私鑰解密
	 * 
	 * @param inPrivate
	 * @param ciphertext
	 */
	public static void decode_public(InputStream inPrivate, String ciphertext) {
		PrivateKey privateKey;

		try {
			privateKey = RSAUtils.loadPrivateKey(inPrivate);
			// 因為RSA加密後的內容經Base64再加密轉換了一下,所以先Base64解密回來再給RSA解密
			byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(ciphertext), privateKey);
			String decryptStr = new String(decryptByte);
			System.out.println("--------解密後的字串-------" + decryptStr);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}

執行效果:

  • 給JButton設定圖片的方法 


jBtn.setIcon(
new ImageIcon(ImageIO.read(Main.class.getClassLoader().
getResource("resources/images/qr_code.png"))));
  •  如何給java工程設定圖片

圖片一定放在,工程的src目錄下,不能放在工程的根目錄下;

usage:獲取工程資原始檔下的圖片:

ImageIO.read(Main.class.getClassLoader().getResource("resources/images/qr_code.png"))

 

   

  • 讀取java工程下的檔案 

      檔案一定放在,工程的src目錄下,不能放在工程的根目錄下;

usage:       

 String publicKey = "rsakey/" + RSAUtils.PUBLIC_KEY;
        String path = Main.class.getClassLoader().getResource(publicKey).getPath();

如何使用這種方式:

String publicKey = "rsakey"+File.separator + RSAUtils.PUBLIC_KEY;

 String path = Main.class.getClassLoader().getResource(publicKey).getPath();

會導致路徑亂碼出現%號等字串,遇見這種情況可以這樣解決:

URLDecoder.decode(path, "UTF-8");//獲取路徑加入File.separator 亂碼,進行解碼就ok;