codeconvert.java

来自「编码转换器,用于把GB2312编码转换成Unicode编码」· Java 代码 · 共 120 行

JAVA
120
字号
package jbbtlh.jbb.tlh;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.UnsupportedEncodingException;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

@SuppressWarnings("serial")
public class CodeConvert extends JFrame {

	private JLabel jltitle = new JLabel("编码转换器");
	private JLabel jlgb2312 = new JLabel("GB2312:");
	private JTextArea jtagb2312 = new JTextArea();
	private JScrollPane jspgb2312 = new JScrollPane(jtagb2312);
	private JLabel jlunicode = new JLabel("Unicode:");
	private JTextArea jtaunicode = new JTextArea();
	private JScrollPane jspunicode = new JScrollPane(jtaunicode);
	private JLabel jlbottom = new JLabel("第二个文本区的内容自动复制到粘贴板,方便使用");

	private CodeConvert() {

		this.setBounds(200, 100, 600, 500);
		this.setTitle("编码转换器");
		this.setLayout(null);
		launchFrame();
		this.setResizable(false);
		this.setVisible(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	private void launchFrame() {
		
		jtagb2312.setLineWrap(true);
		jtaunicode.setLineWrap(true);
		jtaunicode.setEditable(false);
		jtagb2312.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {

			}

			public void keyReleased(KeyEvent e) {

				try {

					String s1 = jtagb2312.getText().trim();
					String s2 = toUnicode(s1);
					jtaunicode.setText(s2);
					setClipboardText(s2);
				} catch (UnsupportedEncodingException e1) {

					e1.printStackTrace();
				}

			}

			public void keyTyped(KeyEvent e) {

			}

		});

		jltitle.setBounds(250, 30, 100, 20);
		this.add(jltitle);

		jlgb2312.setBounds(50, 50, 60, 20);
		this.add(jlgb2312);

		jspgb2312.setBounds(50, 70, 500, 150);
		this.add(jspgb2312);

		jlunicode.setBounds(50, 230, 60, 20);
		this.add(jlunicode);

		jspunicode.setBounds(50, 250, 500, 150);
		this.add(jspunicode);
		
		jlbottom.setBounds(160, 420, 300, 20);
		this.add(jlbottom);
	}

	public String toUnicode(String strText) throws UnsupportedEncodingException {
		char c;
		String strRet = "";
		int intAsc;
		String strHex;
		for (int i = 0; i < strText.length(); i++) {
			c = strText.charAt(i);
			intAsc = (int) c;
			if (intAsc > 128) {
				strHex = Integer.toHexString(intAsc);
				strRet += "\\u" + strHex;
			}
			else {
				strRet = strRet + c;
			}
		}
		return strRet;
	}

	private void setClipboardText(String writeMe) {
		
		Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard(); 
		Transferable tText = new StringSelection(writeMe);
		sysc.setContents(tText, null);
	} 
	
	public static void main(String args[]) {

		new CodeConvert();
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?