Sunday, August 01, 2010

Java Tutorial – Wrap Text into JLabel

Another Java tutorial, hope it will be useful.

Again, this post is from my previous blog post

Coding in Java is my hobby. So I am happy when my subject is about programming in Java. Although I’m still not a great Java programmer, I want to share this tutorial. It is about how to wrap text in to JLabel, so that whenever the text reach the right side of JLabel, it will go to the next line. Sometimes we will face this condition. For example, when we want to create a bunch of information text such as dialog box that display “about” information. We have very long text to display, but if we place it in a JLabel with ordinary process, it will grow horizontally until the end of the text, and never go to the next line.

I created a utility class to solve that problem. This class will be added in my own library, if it is frequently used. Like I have said above, the problem is we have a JLabel and we are confused about how to wrap a String in that label. The concept is simple, we just have to arrange it into html form and place new line tag each time the text reach the right side. Ouch, there is another problem come out, how to detect whether it collide or not. Ok, to answer that question, you can read my source below.

/**
 * DO NOT REMOVE THIS LICENSE
 *
 * This source code is created by Muhammad Fauzil Haqqi.
 * You can use and modify this source code freely but
 * you are forbidden to change or remove this license.
 *
 * Nick  : Haqqi
 * YM    : xp_guitarist
 * Email : fauzil.haqqi@gmail.com
 * Blog  : http://www.fauzilhaqqi.net
 */

import java.awt.FontMetrics;
import java.text.BreakIterator;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

/**
 *
 * @author Haqqi
 */
public class LabelUtil {
  // *******variables area****** //

  // *****constructors area***** //
  /**
   * To prevent the creation of the object
   */
  private LabelUtil() {}

  // ********methods area******* //
  /**
   * Wrap array of String into a label
   * @param label
   * @param text
   */
  public static void wrapTextToLabel(JLabel label, String[] text) {
    // measure the length of font in pixel
    FontMetrics fm = label.getFontMetrics(label.getFont());
    // get container width, you must set the fixed width of
    // the container, i.e. JPanel
    int contWidth = label.getParent().getWidth();
    // to find the word separation
    BreakIterator boundary = BreakIterator.getWordInstance();
    // main string to be added
    StringBuffer m = new StringBuffer("<html>");
    // loop each index of array
    for(String str : text) {
      boundary.setText(str);
      // save each line
      StringBuffer line = new StringBuffer();
      // save each paragraph
      StringBuffer par = new StringBuffer();
      int start = boundary.first();
      // wrap loop
      for(int end = boundary.next(); end != BreakIterator.DONE;
          start = end, end = boundary.next()) {
        String word = str.substring(start,end);
        line.append(word);
        // compare width with font metrics
        int trialWidth = SwingUtilities
            .computeStringWidth(
            fm, line.toString());
        // if bigger, add new line
        if(trialWidth > contWidth) {
          line = new StringBuffer(word);
          par.append("<br />");
        }
        // add new word to paragraphs
        par.append(word);
      }
      // add new line each paragraph
      par.append("<br />");
      // add paragraph into main string
      m.append(par);
    }
    // closed tag
    m.append("</html>");
    label.setText(m.toString());
  }

  /**
   * Wrap a String into a label
   * @param label
   * @param text
   */
  public static void wrapTextToLabel(JLabel label, String text) {
    String[] newText = new String[] {text};
    wrapTextToLabel(label, newText);
  }
}

There are two methods, first is with array of String parameter, and second with single String parameter. There is no difference, just an ordinary overload method. In order to make that method works, there are some adding sequence that you must follow:

  1. Create a container (for example, JPanel) with specific width by call setSize(width, height) method.
  2. Create an empty JLabel then add it to the panel.
  3. After getting the String (from where you get, it’s up to you), call LabelUtil.wrapTextToLabel() method.

For example, I use this text file to create “about” dialog box.

HQ Library v0.001
http://www.fauzilhaqqi.net – 2010

Author: Muhammad Fauzil Haqqi

This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing.

This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing.

This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing. This text is just for testing.

If you have some recomendation, please be free to tell me.

And then, here is an example of main method to show how LabelUtil works.

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;

/**
 *
 * @author Haqqi
 */
public class Tester {
  // *******variables area****** //

  // *****constructors area***** //

  // ********methods area******* //
  public static void main(String[] args) {
    // get default look and feel
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
      Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
    }
    // create new JPanel
    JPanel p = new JPanel();
    // set the border
    p.setBorder(BorderFactory.createEtchedBorder());
    // just set its width
    p.setSize(450, 0);
    // get the text from file. you can change this with your own way
    String[] text = FileUtil.fileRead(FileUtil.setFile("data/about.me"));
    // create new JLabel
    JLabel label = new JLabel();
    // first, add to the panel
    p.add(label);
    // wrap the text
    LabelUtil.wrapTextToLabel(label, text);
    // finally, show the dialog
    JOptionPane.showMessageDialog(null, p, "About this Program",
        JOptionPane.PLAIN_MESSAGE);
  }
}

I read the file using another class of my library, called FileUtil that is already posted here. It returns an array of Strings that will be added in LabelUtil method. If your run that program correctly, it should give this display:

Enjoy coding in Java!! :D

Bahasa keywords: Tutorial Java teks JLabel ganti baris otomatis.


  • jUser
    Thanks.. It's useful for my program.. Keep posting!!!
blog comments powered by Disqus
 

My Tweets

Banners

Tag Cloud

Get Adobe Flash playerPlugin by wpburn.com wordpress themes