How to change clip line ellipses used by Swing when composing text components

By default, Swing uses ellipses "..." to indicate that text has been truncated in JLabel and similar text components. Can this behavior be changed to use a different character string, for example ">"?

Looking through the Swing code, I found in SwingUtilities2 a method called clipString (...), which seems to hardcode the string as "...".

+4
source share
2 answers

The solution I used is as follows:

1) Register a custom LabelUI

2) LabelUI overrides the layoutCL () method to replace Swing ellipses with user-provided ellipses.

public class LabelUI extends MetalLabelUI { private static final int SWING_ELLIPSES_LEN = "...".length(); private static final ComponentUI LABEL_UI_INSTANCE = new LabelUI(); private String displayedText; public static ComponentUI createUI(JComponent c) { return LABEL_UI_INSTANCE; } public String getText() { return displayedText; } protected String layoutCL(JLabel label, FontMetrics fontMetrics, String text, Icon icon, Rectangle viewR, Rectangle iconR, Rectangle textR) { displayedText = super.layoutCL(label, fontMetrics, text, icon, viewR, iconR, textR); String truncationString = (String)label.getClientProperty("LabelUI.truncationString"); if (truncationString != null && !displayedText.equals(text)) { displayedText = displayedText.subSequence(0, displayedText.length() - SWING_ELLIPSES_LEN) + truncationString; } return displayedText; } } 

3) Set new ellipses by setting the client property on the component.

 JLabel component = ... ; component.putClientProperty("LabelUI.truncationString", ">"); 
+1
source

I'm not sure if you can set this to Swing. Consider creating your own JLabel implementation that cuts the string the way you want.

Here you can use the truncation functions from SwingUtilities. You can start by copying by pasting code from it, which is usually a good start.

I think you need to extend the paintComponent method for JLabel, measure the FontMetrics, and determine if the label requires truncation. If it sets the text to a truncated value. Remember to save a non-truncated value in a field or so.

+1
source

All Articles