Example #1
0
 /**
  * Shorten the given text <code>t</code> so that its length doesn't exceed the given width. The
  * default implementation replaces characters in the center of the original string with an
  * ellipsis ("..."). Override if you need a different strategy.
  *
  * @param gc the gc to use for text measurement
  * @param t the text to shorten
  * @param width the width to shorten the text to, in pixels
  * @return the shortened text
  */
 protected String shortenText(GC gc, String t, int width) {
   if (t == null) return null;
   int w = gc.textExtent(ELLIPSIS, DRAW_FLAGS).x;
   if (width <= w) return t;
   int l = t.length();
   int max = l / 2;
   int min = 0;
   int mid = (max + min) / 2 - 1;
   if (mid <= 0) return t;
   TextLayout layout = new TextLayout(getDisplay());
   layout.setText(t);
   mid = validateOffset(layout, mid);
   while (min < mid && mid < max) {
     String s1 = t.substring(0, mid);
     String s2 = t.substring(validateOffset(layout, l - mid), l);
     int l1 = gc.textExtent(s1, DRAW_FLAGS).x;
     int l2 = gc.textExtent(s2, DRAW_FLAGS).x;
     if (l1 + w + l2 > width) {
       max = mid;
       mid = validateOffset(layout, (max + min) / 2);
     } else if (l1 + w + l2 < width) {
       min = mid;
       mid = validateOffset(layout, (max + min) / 2);
     } else {
       min = max;
     }
   }
   String result =
       mid == 0
           ? t
           : t.substring(0, mid) + ELLIPSIS + t.substring(validateOffset(layout, l - mid), l);
   layout.dispose();
   return result;
 }
 public static void main(String[] args) {
   Display display = new Display();
   final Shell shell = new Shell(display, SWT.SHELL_TRIM | SWT.DOUBLE_BUFFERED);
   shell.setText("Underline, Strike Out");
   Font font = shell.getFont();
   String text = "Here is some text that is underlined or struck out or both.";
   final TextLayout layout = new TextLayout(display);
   layout.setText(text);
   TextStyle style1 = new TextStyle(font, null, null);
   style1.underline = true;
   layout.setStyle(style1, 26, 35);
   TextStyle style2 = new TextStyle(font, null, null);
   style2.strikeout = true;
   layout.setStyle(style2, 40, 49);
   TextStyle style3 = new TextStyle(font, null, null);
   style3.underline = true;
   style3.strikeout = true;
   layout.setStyle(style3, 54, 57);
   shell.addListener(
       SWT.Paint,
       new Listener() {
         @Override
         public void handleEvent(Event event) {
           Point point = new Point(10, 10);
           int width = shell.getClientArea().width - 2 * point.x;
           layout.setWidth(width);
           layout.draw(event.gc, point.x, point.y);
         }
       });
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) display.sleep();
   }
   layout.dispose();
   display.dispose();
 }