Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Advanced
Sep 8, 1999

Aligned Columns in java.awt.List

You can use, or extend, java.awt.List to create a simple multi-column list. In order to do so, you need to use a fixed character width font set like Courier.

Suppose you have a java.awt.List object, called multiList sitting on your GUI, and you want your multiList to have three columns each of length 20 characters:

 
//define some data members
private final static String PAD_CHARACTER = " "; //space
private int[] widths ={20,20,20};
private String[] padStrings = new String[widths.length];
Now, create as many padding strings as your columns, and each as wide as your widths:
 
    for(int i=0; i<widths.length; i++)
    {
        //use StringBuffer for efficiency
        StringBuffer sBuff = new StringBuffer();
        for(int j=0; j<widths[i]; j++)
        {
          sBuff.append(PAD_CHARACTER);
        }
        padStrings[i]=sBuff.toString();
    }
Say you want to insert ("999999","JOHN","DOE") as a row of data, and you want them to be bold:
 
    String[] entries = new String[3];
    entries[0] = "JOHN";
    entries[1] =  "DOE";
    entries[2] = "999 WHICHEVER STREET";
    multiList.setFont(new Font("Courier", Font.BOLD, 12));
    insertRow(multiList,entries);
Let's insert another row of data just for fun:
 
    entries[0] = "JANETTE";
    entries[1] =  "DOVE";
    entries[2] = "999 SAME STREET";
    insertRow(multiList,entries);
Note that before calling insertRow(...) method, you should check if the length of your entries corresponds to the width of each column, and if not take appropriate action.

Voila, you have your multiList all aligned for three columns.

The following is the code for method insertRow(...):

 
    public void insertRow(List aList, String[] rowItems) 
    {
        StringBuffer sb = new StringBuffer();
        for(int item=0; item<rowItems.length; item++)
        {
	//use StringBuffer for efficiency
            sb.append(rowItems[item]);
 
sb.append(padStrings[1].substring(0,widths[1]-rowItems[item].length()));   
        }

        aList.addItem(sb.toString());
    }
Behrouz Fallahi
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap