Cut off the text of a JLabel on the left

This doesn’t provide the leading ellipsis (…), but at least it is simple and clean. You can put the JLabel in a JViewport and keep it scrolled to the end at all times:

JViewport viewport = new JViewport();
viewport.setView(label);
viewport.addComponentListener(new ComponentAdapter() {
    @Override
    public void componentResized(ComponentEvent event) {
        int width = viewport.getWidth();
        Dimension size = label.getPreferredSize();
        viewport.setViewPosition(new Point(size.width - width, 0));
    }
});

Using the excellent answer from trashgod (https://stackoverflow.com/a/3597688/567496), here is a simple implementation of a BasicLabelUI that creates a left-side ellipsis.

It does use Apache's StringUtils.reverse(text), but only for convenience. It could be replaced with calls to StringBuilder(text).reverse().toString().

static class LeftEllipsisUI extends BasicLabelUI {
    @Override
    protected String layoutCL(JLabel label, FontMetrics fontMetrics, String text, Icon icon, Rectangle viewR, Rectangle iconR, Rectangle textR) {
        return StringUtils.reverse(super.layoutCL(label, fontMetrics, StringUtils.reverse(text), icon, viewR, iconR, textR));
    }
}

Tags:

Java

Swing

Jlabel