Come rendere il testo in una casella e sostituire l'eccesso con tre punti
Domanda
Rendo il testo con un renderer di celle di tabella personalizzato e voglio tagliare il testo disegnato se superasse la larghezza della cella corrente, passando a " Questo testo è lungo ... " tipo di rappresentazione, in cui i tre punti alla fine non escono mai dal rettangolo di selezione. Il mio attuale algoritmo è il seguente:
FontMetrics fm0 = g2.getFontMetrics();
int h = fm0.getHeight();
int ellw = fm0.stringWidth("\u2026");
int titleWidth = fm0.stringWidth(se.title);
if (titleWidth > getWidth()) {
for (int i = se.title.length() - 1; i > 0; i--) {
String tstr = se.title.substring(0, i);
int tstrw = fm0.stringWidth(tstr);
if (tstrw + ellw < getWidth()) {
g2.drawString(tstr, 2, h);
g2.drawString("\u2026", 2 + tstrw, h);
break;
}
}
} else {
g2.drawString(se.title, 2, h);
}
Esiste un modo migliore per determinare quanti caratteri dovrei drawString ()
prima di passare al carattere ... (u2026)?
Soluzione
Questo è il comportamento predefinito del renderer predefinito per una tabella, quindi non sono sicuro di aver capito il motivo per farlo.
Ma ho creato un renderer per punti a sinistra ("il testo ... è troppo lungo") che mostra un modo più completo di fare ciò che vuoi poiché tiene conto di un possibile bordo sul renderer e la spaziatura intercellulare del renderer. Dai un'occhiata al LeftDotRenderer .
Altri suggerimenti
Non riesco a pensare a un altro modo per ottenere l'effetto desiderato, ma dovresti essere in grado di sostituire le 2 chiamate drawString () con una. È da un po 'che non scrivo Java ma penso che dovrebbe funzionare quanto segue.
A proposito, ho cambiato i nomi delle variabili in modo da poter leggere il codice. : P
FontMetrics metrics = g2.getFontMetrics();
int fontHeight = metrics.getHeight();
int titleWidth = metrics.stringWidth(se.title);
if (titleWidth > getWidth()) {
String titleString;
for (int i = se.title.length() - 1; i > 0; i --) {
titleString = se.title.substring(0, i) + "\u2026";
titleWidth = metrics.stringWidth(titleString);
if (titleWidth < getWidth()) {
g2.drawString(titleString, 2, fontHeight);
break;
}
}
} else {
g2.drawString(se.title, 2, fontHeight);
}