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
See also  How to Create and Deploy QR Codes Online: A Comprehensive Guide

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist