May 20, 2011

Displaying Sinhala in JTextArea

When I first tried to display Sinhala characters in a JTextArea, I got the following result, where all the Sinhala letters were replaced by boxes.

Original text : තමා_PRP හයිටිය_NNPI අතහැර_VNF පලා_VNF ගියේ_VP කැමැත්තකින්

The reason for this is that, it does not render Sinhala fonts.It is not a problem with detection of encoding. You can simply check the system default encoding with code below.
This produced with UTF-8 encoding, which was ok for my requirement.

Now this meant, that the problem is in using an appropriate font for the JTextArea.
File fontFile = new File(fontpath); //load the font file
Font newFont = Font.createFont(Font.TRUETYPE_FONT, fontFile);
txtOutput.setFont(newFont); //set the font to JTextArea

The above code will add a font to a JTextArea. Out of the many fonts I tried, only "dinamina.ttf" rendered properly. Even lklug did not provide proper results (It only rendered Sinhala and English characters were not at all displayed). Following is the final output.

Download sinhala fonts from here

Updates :

  • Found our that lklug has only Sinhala fonts
  • Also Bhashitha is another font that worked fine with me
  • May 1, 2011

    for, while and do..while

    for, while and do..while are the three types of loops available for almost all imperative languages. But the concept is same for all of them and they only carry slight variations is syntax.

    One of the concerns when writing a loop is to identify which of the above three is most suitable. It is important if efficiency is an expectation of your program.

      //code here

      //code here

    for( i = 0; i < 10; i++){
      //code here

    while vs do..while
    The while and do..while loops both loop until a condition is false. But the difference between them is that the while loop will check the condition before the first iteration and the do..while will perform the first iteration and then after check the condition. Therefore the change is in the first iteration and after it is finished, there is no difference between the two loops.

    while vs for

    A common mis-use of the while loop is using a counter within it. That is use a counter to keep track of the number of iterations of the loop and making sure to exit the loop when the counter is exceeded.

    i = 0;
    while ( i < 5){
      //code here

    The purpose of the for loop is to be used in such situations.

    for ( int i = 0; i < 5; i++){
      //code here

    Therefore, the main difference between the two would be to use the for loop when the number of iterations is known and use the while or do..while when unknown. But there is no real difference in efficiency for a situation as above. Hence, I believe its more of de facto.