Is there a way to add an ellipsis to a label if the text doesn’t fit the area, as in HTML?

1 answer

Staff August 20, 2015

There is no special API that can do it. But you can try to control the length of text to detect if the given label fits its area and than does what you need. It is better to do by implementing an own text render. For instance, find below the code samples that shows “…” if a label cannot be shown completely, additionally the label show the full text in tooltip:

 var MyStringRender = zebra.Class(zebra.ui.StringRender, [
function paint(g,x,y,w,h,d) {
if (this.stringWidth > w) {
this.showAsCut = true;
var dotsLen = this.font.stringWidth("...");
// clip original label to have a place to show "..."
try {
g.save();
g.clipRect(x, y, w - dotsLen, h);
this.$super(g,x,y,w,h,d);
} finally { g.restore();}
g.fillText("...", x + w - dotsLen, y);
}
else {
this.showAsCut = false;
this.$super(g,x,y,w,h,d);
}
}
]);

// create canvas
var root = (new zebra.ui.zCanvas(400, 500)).root;
root.setLayout(new zebra.layout.FlowLayout(8));
root.setPadding(8);

root.add(new zebra.ui.Label(new MyStringRender("Test sdsdsd"), [
function(t) {
this.$super(t);
this.setPadding(8);
this.setBorder("plain");
this.setPreferredSize(60, -1);
this.tooltipLab = new zebra.ui.Label();
this.tooltipLab.setValue(this.getValue());
this.tooltipLab.setBorder("plain");
this.tooltipLab.setBackground("yellow");
this.tooltipLab.setPadding(2);
this.tooltipLab.setFont(zebra.ui.smallFont);
},

function getTooltip() {
return this.view.showAsCut === true ? this.tooltipLab : null;
}
]));

 

#1

Please login or Register to Submit Answer