Share this page 

Set the listbox widthTag(s): AWT


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);
    }
}