4

By default Swing uses ellipses "..." to indicate that text has been truncated in JLabel and similar text based components. Is it possible to change this behavior to use a different character string, for example ">"?

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

bakkal
  • 54,350
  • 12
  • 131
  • 107
Ivo Bosticky
  • 6,338
  • 6
  • 34
  • 35

2 Answers2

1

The solution I used goes like this:

1) Register a custom LabelUI

2) The LabelUI overrides the layoutCL() method to replace the Swing ellipses with user supplied 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) Supply the new ellipses by setting a client property on the component.

JLabel component = ... ;
component.putClientProperty("LabelUI.truncationString", ">");
Ivo Bosticky
  • 6,338
  • 6
  • 34
  • 35
1

I am not sure you can set that in Swing. Consider making your own JLabel implementation that truncates the string as you want it.

Here you could use the truncation functions from SwingUtilities. You could begin with copy pasting the code from it, that usually is a good start.

I think you need to extend the paintComponent method of the JLabel, measure the FontMetrics and determine if the label needs truncation. If it does set the text to the truncated value. Remember to keep the not-truncated value in a field or so.

Jes
  • 2,748
  • 18
  • 22