Unicode conversion

Lecture



Most java programmers sooner or later face the problem of localization of the created products. And, despite the fact that the method of localization is described quite well, for example, you can refer to the manual at

http://java.sun.com/docs/books/tutorial/i18n/index.html , there is a problem directly converting strings to unicode. To simplify this operation a simple utility was created that performs the conversion and allows you to copy the resulting lines to the clipboard. Download this program at http://www.forjava.dev.juga.ru/downloads.html   . The archive package contains source codes and executable classes. The basis of the transcoding algorithm was the method:

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);

}

class:

http://java.sun.com/docs/books/tutorial/i18n/text/example-1dot1/UnicodeFormatter.java

.

The program is a panel split into two parts (see Fig. 1).

  Unicode conversion

Fig. one.

Unicode string conversion example

In the top panel, enter the text that you want to recode, while in the bottom panel we immediately get its counterpart in Unicode. For ease of copying, context menu handlers are added that are invoked using the mouse.

To handle keystrokes, keystroke and release listeners have been added to the source container, which call the transcoding method:

. . .

// Listeners for pressing and releasing keys

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));

}

// Directly recoding

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

}

. . .


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Object oriented programming

Terms: Object oriented programming