如果以純代碼的形式進行JAVA的圖形用戶界面編輯,將是一件非常痛苦的事,博主在學習過程中發現了JAVA GUI編輯神器——WindowBuilder,提供可視化的編輯界面,控件的添加、排版只需使用鼠標進行拖拽即可。
安裝
首先進入WindowBuilder網站http://www.eclipse.org/windowbuilder/,接着點擊Download
選擇對應的Eclipse版本,博主的是4.7(Oxygen),點擊link,複製地址欄內的網址
打開Eclipse,點擊頂欄Help內的Install New Software,將網址拷貝到Work with中並回車,勾選所有組件,一路點擊Next即可進行安裝。
安裝完成後,點擊Eclipse頂欄的File,選擇New中的other,在彈出的新建框內若有WindowBuilder選項則證明安裝成功。
簡單示例
博主接下來爲大家實現一個Swing窗體應用程序(網絡程序設計實驗教程(Java語言)),實現的功能是:1. 將字符序列文本框中的字符串以對應的編碼方案進行編碼,並存儲到字節數組中,最後將字節數組中的字節以十六進制的方式表示;2. 將字符序列文本框中的十六進制方式表示的字節數組以對應的編碼方案進行解碼,並將解碼後得到的字符串顯示出來。
新建一個名爲TestEncoding的Java項目,在項目中用WindowBuilder創建一個Application Window應用程序,命名爲AppMain,再將主窗體重命名爲frmMain,窗體標題改爲“編碼解碼示例”。
拖動工具箱中的控件進行排版,(將getContentPane()屬性中的layout設置爲Absolute layout,可將控件隨意拖拽到你指定的位置)設置相應控件屬性如下表所示。
控件 | 名稱 | 屬性 | 值 |
---|---|---|---|
按鈕JButton | btnGBKEncode | Text | GBK編碼結果 |
按鈕JButton | btnUTF8Encode | Text | UTF-8編碼結果 |
按鈕JButton | btnGBKDncode | Text | GBK解碼結果 |
按鈕JButton | btnUTF8Dncode | Text | UTF-8解碼結果 |
文本框JTextField | tfChars | ||
文本框JTextField | tfBytesGBK | Enabled | False |
文本框JTextField | tfBytesUTF8 | Enabled | False |
文本框JTextField | tfBytes | ||
文本框JTextField | tfCharsGBK | Enabled | False |
文本框JTextField | tfCharsUTF8 | Enabled | False |
編碼功能的實現
雙擊按鈕btnGBKEncode,在函數內添加如下代碼:
String str = tfChars.getText();
Charset cs = Charset.forName("GBK");
ByteBuffer buffer = cs.encode(str);
String hexStr = "";
while(buffer.remaining()>0) {
hexStr += Integer.toHexString(buffer.get()&0xFF).toUpperCase()+" ";
}
tfBytesGBK.setText(hexStr);
雙擊按鈕btnUTF8Encode,在函數內添加如下代碼:
String str = tfChars.getText();
String hexStr = "";
try {
byte[] bytes = str.getBytes("UTF-8");
for(int i=0;i<bytes.length;i++) {
hexStr += Integer.toHexString(bytes[i]&0xFF).toUpperCase()+" ";
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}finally {
tfBytesUTF8.setText(hexStr);
}
解碼功能的實現
雙擊按鈕btnGBKDecode,添加如下代碼:
String hexStr = tfBytes.getText();
String[] strs = hexStr.split(" ");
byte[] array = new byte[strs.length];
for(int i=0;i<strs.length;i++) {
array[i] = (byte)(Integer.valueOf(strs[i],16).intValue());
}
Charset cs = Charset.forName("GBK");
CharBuffer buffer = cs.decode(ByteBuffer.wrap(array));
tfCharsGBK.setText(buffer.toString());
雙擊按鈕btnUTF8Decode,添加如下代碼:
String hexStr = tfBytes.getText();
String[] strs = hexStr.split(" ");
byte[] bytes = new byte[strs.length];
for(int i=0;i<strs.length;i++) {
bytes[i] = (byte)(Integer.valueOf(strs[i],16).intValue());
}
String str = "";
try {
str = new String(bytes,"UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}finally {
tfCharsUTF8.setText(str);
}
最終效果如下:
由此可見在網絡傳輸過程中解碼方式如果錯誤,得到的結果也就面目全非了。
這篇博客更多是引路用的,更多內容請上官網查看教程。