How to set SWT List height in rows?

I have a Composite based class that includes an instance of SWT List . Using the default settings, the list contains five lines in my WinXP system. Without relying on hard-coded pixel values ​​or DPI parameters and the like, how to set the height of the list (and the surrounding composite) to a fixed number of lines, say 3, without any added internal fields?

 public FileSetBox(Composite parent, int style) { super(parent, style); setLayout(new FillLayout()); this.list = new List(this, SWT.V_SCROLL); ... } 

Update:

The following works, but do not take into account the height added by the border, which leads to the fact that parts of the last line will be covered. Any ideas how to calculate this too?

 public FileSetBox(Composite parent, int style) { ... GC gc = new GC(this); gc.setFont(this.list.getFont()); this.preferredHeight = gc.getFontMetrics().getHeight() * 3; gc.dispose(); ... } @Override public Point computeSize(int arg0, int arg1) { Point size = super.computeSize(arg0, arg1); return new Point(size.x, this.preferredHeight); } 
+4
source share
2 answers

Can't you use list.getBorderWidth () and list.getItemHeight () to get the height?

+4
source
  public FileSetBox (Composite parent, int style)
 {
     super (parent, style);

     setLayout (new GridLayout (1, false));

     this.list = new List (this, SWT.V_SCROLL);

     GridData data = new GridData (GridData.FILL_BOTH);
     data.heightHint = 10 * ((List) control) .getItemHeight ();  // height for 10 rows
     data.widthHint = getStringWidth (25, list);  // width enough to display 25 chars
     list.setLayoutData (data);

     ...
 }

     public static int getStringWidth (int nChars, Control control) {
         GC gc = new GC (control);
         gc.setFont (control.getFont ());
         FontMetrics fontMetrics = gc.getFontMetrics ();
         gc.dispose ();
         return nChars * fontMetrics.getAverageCharWidth ();
     }

+1
source

Source: https://habr.com/ru/post/1286357/


All Articles