Jump to Real's How-to Main page

Set the listbox width

The width can be specified via the preferredSize method. This class lets you specify a font (fixed pitch) and calculate the appropriate width in pixels.
class myListbox extends List {
  int width;
  int height;
  public myListbox(int r, int n, boolean m){
    // (r) line number, (n) width, (m) multiselect
    this(r, n, m, new Font("Courier", Font.BOLD, 10));
    width = n;
    height = r;
    }
        
  public myListbox(int r, int n, boolean m, Font f){
    super(r,m);
    width = n;
    height = r;
    setFont(f);
    }

  public Dimension preferredSize (){
    FontMetrics fm=getFontMetrics(getFont());
    // the character W used as reference
    return new Dimension
           (fm.charWidth('W')*width, fm.getHeight()*height);
    }
}

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]