devxlogo

Aligned Columns in java.awt.List

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 membersprivate final static String PAD_CHARACTER = " "; //spaceprivate 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

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

devx-admin

Share the Post: