|
Written by Maksym Nesen
|
|
Tuesday, 04 November 2008 15:08 |
In many cases there is a nessesety to transform some local text encodings into the Unicode. Even thou methods of this transformation are well described, there are some problems with direct realisation. To simplify this operation one can use a method, which is described below:
static public String charToHex(char c) {
// Returns hex String representation of char c
byte hi = (byte) (c >>> 8);
byte lo = (byte) (c & 0xff);
return byteToHex(hi) + byteToHex(lo);
}
This method belongs to the class http://java.sun.com/docs/books/tutorial/i18n/text/example-1dot1/UnicodeFormatter.java To simplify work with mouse in this example, one can implement following MouseListeners: . . .
srcText.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(KeyEvent e) {
srcText_keyReleased(e);
}
public void keyTyped(KeyEvent e) {
srcText_keyTyped(e);
}
});
private void srcText_keyReleased(KeyEvent e) {
convertToUnicode();
}
private void srcText_keyTyped(KeyEvent e) {
convertToUnicode();
}
private void convertToUnicode() {
String source = srcText.getText();
char[] ca = source.toCharArray();
targetText.setText(convertChars(ca));
}
public String convertChars(char[] array) {
StringBuffer s = new StringBuffer();
for (int k = 0; k < array.length; k++) {
byte hi = (byte) (array[k] >>> 8);
if (hi != 0) {
s.append("\u" + UnicodeFormatter.charToHex(array[k]));
} else {
s.append(array[k]);
}
}
return s.toString();
}
|