JComboBox Tooltip
Posted by blogmeister on
July 3, 2011
You wonder why there may be a need to have a tooltip inside a JComboBox. What if your item is very long like the image shown below?
This where tooltips come in handy unless you plan to have your JComboBox display items in multi-line if they are very long but that won’t look good. A tooltip is the best solution and the way to go about this is to assign a renderer to the JComboBox that does this.
This class does the trick. You only need to instantiate this and assign it to the JComboBox by calling the setRenderer() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class ComboBoxToolTipRenderer extends BasicComboBoxRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); if (-1 < index) { list.setToolTipText(list.getSelectedValue().toString()); } } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } setFont(list.getFont()); setText((value == null) ? "" : value.toString()); return this; } } |
MultiLine JLabel
Posted by blogmeister on
January 13, 2011
To create a multi-line JLabel, Samuel Sjoberg provided a custom class that extended the BasicLabelUI class in order to paint text and wrap them to multiple lines rather than displaying the text as one line and truncated with a …
To use the class, just do
|
1 |
label.setUI(MultiLineLabelUI.labelUI); |
Here is the full MultiLineLabelUI class.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 |
public class MultiLineLabelUI extends BasicLabelUI implements ComponentListener { /** Shared instance of the UI delegate. */ public static LabelUI labelUI = new MultiLineLabelUI(); /** * Client property key used to store the calculated wrapped lines on the * JLabel. */ public static final String PROPERTY_KEY = "WrappedText"; // Static references to avoid heap allocations. protected static Rectangle paintIconR = new Rectangle(); protected static Rectangle paintTextR = new Rectangle(); protected static Rectangle paintViewR = new Rectangle(); protected static Insets paintViewInsets = new Insets(0, 0, 0, 0); /** Font metrics of the JLabel being rendered. */ protected FontMetrics metrics; /** Default size of the lines list. */ protected static int defaultSize = 4; /** * Get the shared UI instance. * * @param c * the component about to be installed * @return the shared UI delegate instance */ public static ComponentUI createUI(JComponent c) { return labelUI; } /** {@inheritDoc} */ @Override protected void uninstallDefaults(JLabel c) { super.uninstallDefaults(c); clearCache(c); } /** {@inheritDoc} */ @Override protected void installListeners(JLabel c) { super.installListeners(c); c.addComponentListener(this); } /** {@inheritDoc} */ @Override protected void uninstallListeners(JLabel c) { super.uninstallListeners(c); c.removeComponentListener(this); } /** * Clear the wrapped line cache. * * @param l * the label containing a cached value */ protected void clearCache(JLabel l) { l.putClientProperty(PROPERTY_KEY, null); } /** {@inheritDoc} */ @Override public void propertyChange(PropertyChangeEvent e) { super.propertyChange(e); final String name = e.getPropertyName(); if (name.equals("text") || "font".equals(name)) { clearCache((JLabel) e.getSource()); } } /** * Calculate the paint rectangles for the icon and text for the passed * label. * * @param l * a label * @param fm * the font metrics to use, or <code>null</code> to get the font * metrics from the label * @param width * label width * @param height * label height */ protected void updateLayout(JLabel l, FontMetrics fm, int width, int height) { if (fm == null) { fm = l.getFontMetrics(l.getFont()); } metrics = fm; String text = l.getText(); Icon icon = l.getIcon(); Insets insets = l.getInsets(paintViewInsets); paintViewR.x = insets.left; paintViewR.y = insets.top; paintViewR.width = width - (insets.left + insets.right); paintViewR.height = height - (insets.top + insets.bottom); paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0; paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0; layoutCL(l, fm, text, icon, paintViewR, paintIconR, paintTextR); } protected void prepareGraphics(Graphics g) { } /** {@inheritDoc} */ @Override public void paint(Graphics g, JComponent c) { // parent's update method fills the background prepareGraphics(g); JLabel label = (JLabel) c; String text = label.getText(); Icon icon = (label.isEnabled()) ? label.getIcon() : label .getDisabledIcon(); if ((icon == null) && (text == null)) { return; } FontMetrics fm = g.getFontMetrics(); updateLayout(label, fm, c.getWidth(), c.getHeight()); if (icon != null) { icon.paintIcon(c, g, paintIconR.x, paintIconR.y); } if (text != null) { View v = (View) c.getClientProperty("html"); if (v != null) { // HTML view disables multi-line painting. v.paint(g, paintTextR); } else { // Paint the multi line text paintTextLines(g, label, fm); } } } /** * Paint the wrapped text lines. * * @param g * graphics component to paint on * @param label * the label being painted * @param fm * font metrics for current font */ protected void paintTextLines(Graphics g, JLabel label, FontMetrics fm) { List<String> lines = getTextLines(label); // Available component height to paint on. int height = getAvailableHeight(label); int textHeight = lines.size() * fm.getHeight(); while (textHeight > height) { // Remove one line until no. of visible lines is found. textHeight -= fm.getHeight(); } paintTextR.height = Math.min(textHeight, height); paintTextR.y = alignmentY(label, fm, paintTextR); int textX = paintTextR.x; int textY = paintTextR.y; for (Iterator<String> it = lines.iterator(); it.hasNext() && paintTextR.contains(textX, textY + getAscent(fm)); textY += fm .getHeight()) { String text = it.next().trim(); if (it.hasNext() && !paintTextR.contains(textX, textY + fm.getHeight() + getAscent(fm))) { // The last visible row, add a clip indication. text = clip(text, fm, paintTextR); } int x = alignmentX(label, fm, text, paintTextR); if (label.isEnabled()) { paintEnabledText(label, g, text, x, textY); } else { paintDisabledText(label, g, text, x, textY); } } } /** * Returns the available height to paint text on. This is the height of the * passed component with insets subtracted. * * @param l * a component * @return the available height */ protected int getAvailableHeight(JLabel l) { l.getInsets(paintViewInsets); return l.getHeight() - paintViewInsets.top - paintViewInsets.bottom; } /** * Add a clip indication to the string. It is important that the string * length does not exceed the length or the original string. * * @param text * the to be painted * @param fm * font metrics * @param bounds * the text bounds * @return the clipped string */ protected String clip(String text, FontMetrics fm, Rectangle bounds) { // Fast and lazy way to insert a clip indication is to simply replace // the last characters in the string with the clip indication. // A better way would be to use metrics and calculate how many (if any) // characters that need to be replaced. if (text.length() < 3) { return "..."; } return text.substring(0, text.length() - 3) + "..."; } /** * Establish the vertical text alignment. The default alignment is to center * the text in the label. * * @param label * the label to paint * @param fm * font metrics * @param bounds * the text bounds rectangle * @return the vertical text alignment, defaults to CENTER. */ protected int alignmentY(JLabel label, FontMetrics fm, Rectangle bounds) { final int height = getAvailableHeight(label); int textHeight = bounds.height; if (label instanceof MultiLineLabel) { int align = ((MultiLineLabel) label).getVerticalTextAlignment(); switch (align) { case JLabel.TOP: return getAscent(fm) + paintViewInsets.top; case JLabel.BOTTOM: return getAscent(fm) + height - paintViewInsets.top + paintViewInsets.bottom - textHeight; default: } } // Center alignment int textY = paintViewInsets.top + (height - textHeight) / 2 + getAscent(fm); // set top by default textY = paintViewInsets.top; return Math.max(textY, getAscent(fm) + paintViewInsets.top); } private static int getAscent(FontMetrics fm) { return fm.getAscent() + fm.getLeading(); } /** * Establish the horizontal text alignment. The default alignment is left * aligned text. * * @param label * the label to paint * @param fm * font metrics * @param s * the string to paint * @param bounds * the text bounds rectangle * @return the x-coordinate to use when painting for proper alignment */ protected int alignmentX(JLabel label, FontMetrics fm, String s, Rectangle bounds) { if (label instanceof MultiLineLabel) { int align = ((MultiLineLabel) label).getHorizontalTextAlignment(); switch (align) { case JLabel.RIGHT: return bounds.x + paintViewR.width - fm.stringWidth(s); case JLabel.CENTER: return bounds.x + paintViewR.width / 2 - fm.stringWidth(s) / 2; default: return bounds.x; } } return bounds.x; } /** * Check the given string to see if it should be rendered as HTML. Code * based on implementation found in * <code>BasicHTML.isHTMLString(String)</code> in future JDKs. * * @param s * the string * @return <code>true</code> if string is HTML, otherwise <code>false</code> */ private static boolean isHTMLString(String s) { if (s != null) { if ((s.length() >= 6) && (s.charAt(0) == '<') && (s.charAt(5) == '>')) { String tag = s.substring(1, 5); return tag.equalsIgnoreCase("html"); } } return false; } /** {@inheritDoc} */ @Override public Dimension getPreferredSize(JComponent c) { Dimension d = super.getPreferredSize(c); JLabel label = (JLabel) c; if (isHTMLString(label.getText())) { return d; // HTML overrides everything and we don't need to process } // Width calculated by super is OK. The preferred width is the width of // the unwrapped content as long as it does not exceed the width of the // parent container. if (c.getParent() != null) { // Ensure that preferred width never exceeds the available width // (including its border insets) of the parent container. Insets insets = c.getParent().getInsets(); Dimension size = c.getParent().getSize(); if (size.width > 0) { // If width isn't set component shouldn't adjust. d.width = size.width - insets.left - insets.right; } } updateLayout(label, null, d.width, d.height); // The preferred height is either the preferred height of the text // lines, or the height of the icon. d.height = Math.max(d.height, getPreferredHeight(label)); return d; } /** * The preferred height of the label is the height of the lines with added * top and bottom insets. * * @param label * the label * @return the preferred height of the wrapped lines. */ protected int getPreferredHeight(JLabel label) { int numOfLines = getTextLines(label).size(); Insets insets = label.getInsets(paintViewInsets); return numOfLines * metrics.getHeight() + insets.top + insets.bottom; } /** * Get the lines of text contained in the text label. The prepared lines is * cached as a client property, accessible via {@link #PROPERTY_KEY}. * * @param l * the label * @return the text lines of the label. */ @SuppressWarnings("unchecked") protected List<String> getTextLines(JLabel l) { List<String> lines = (List<String>) l.getClientProperty(PROPERTY_KEY); if (lines == null) { lines = prepareLines(l); l.putClientProperty(PROPERTY_KEY, lines); } return lines; } /** {@inheritDoc} */ public void componentHidden(ComponentEvent e) { // Don't care } /** {@inheritDoc} */ public void componentMoved(ComponentEvent e) { // Don't care } /** {@inheritDoc} */ public void componentResized(ComponentEvent e) { clearCache((JLabel) e.getSource()); } /** {@inheritDoc} */ public void componentShown(ComponentEvent e) { // Don't care } /** * Prepare the text lines for rendering. The lines are wrapped to fit in the * current available space for text. Explicit line breaks are preserved. * * @param l * the label to render * @return a list of text lines to render */ protected List<String> prepareLines(JLabel l) { List<String> lines = new ArrayList<String>(defaultSize); String text = l.getText(); if (text == null) { return null; // Null guard } PlainDocument doc = new PlainDocument(); try { doc.insertString(0, text, null); } catch (BadLocationException e) { return null; } Element root = doc.getDefaultRootElement(); for (int i = 0, j = root.getElementCount(); i < j; i++) { wrap(lines, root.getElement(i)); } return lines; } /** * If necessary, wrap the text into multiple lines. * * @param lines * line array in which to store the wrapped lines * @param elem * the document element containing the text content */ protected void wrap(List<String> lines, Element elem) { int p1 = elem.getEndOffset(); Document doc = elem.getDocument(); for (int p0 = elem.getStartOffset(); p0 < p1;) { int p = calculateBreakPosition(doc, p0, p1); try { lines.add(doc.getText(p0, p - p0)); } catch (BadLocationException e) { throw new Error("Can't get line text. p0=" + p0 + " p=" + p); } p0 = (p == p0) ? p1 : p; } } /** * Calculate the position on which to break (wrap) the line. * * @param doc * the document * @param p0 * start position * @param p1 * end position * @return the actual end position, will be <code>p1</code> if content does * not need to wrap, otherwise it will be less than <code>p1</code>. */ protected int calculateBreakPosition(Document doc, int p0, int p1) { Segment segment = SegmentCache.getSegment(); try { doc.getText(p0, p1 - p0, segment); } catch (BadLocationException e) { throw new Error("Can't get line text"); } int width = paintTextR.width; int p = p0 + Utilities.getBreakLocation(segment, metrics, 0, width, null, p0); SegmentCache.releaseSegment(segment); return p; } /** * Static singleton {@link Segment} cache. * * @see javax.swing.text.SegmentCache * * @author Samuel Sjoberg */ protected static final class SegmentCache { /** Reused segments. */ private ArrayList<Segment> segments = new ArrayList<Segment>(2); /** Singleton instance. */ private static SegmentCache cache = new SegmentCache(); /** Private constructor. */ private SegmentCache() { } /** * Returns a <code>Segment</code>. When done, the <code>Segment</code> * should be recycled by invoking {@link #releaseSegment(Segment)}. * * @return a <code>Segment</code>. */ public static Segment getSegment() { int size = cache.segments.size(); if (size > 0) { return cache.segments.remove(size - 1); } return new Segment(); } /** * Releases a <code>Segment</code>. A segment should not be used after * it is released, and a segment should never be released more than * once. */ public static void releaseSegment(Segment segment) { segment.array = null; segment.count = 0; cache.segments.add(segment); } } } |









