Allora, ho modificato un esempio che avevo fatto qualche tempo fa per provare Document, e mi sono risparmiato un mal di testa con i lineWrap e quant'altro - forse la cosa migliore.
codice:
import javax.swing.*;
import javax.swing.text.*;
/**
*
* @author Andrea
*/
public class LineWrapTest extends JFrame {
private JTextArea ta;
private static final int MAX_LENGTH = 20;
private class MyDocument extends PlainDocument {
private int max_length;
public MyDocument(int max_length) {
this.max_length = max_length;
}
public void insertString(int offset, String string, AttributeSet attr) throws BadLocationException {
// voglio al massimo il doppio dei caratteri a disposizione per ogni riga
// essendoci in totale 2 righe.
string = string.substring(0, max_length*2-1);
// controllo che carattere occupa la posizione "max_length" e determino
// qual è la posizione del primo spazio prima di tale posizione
char c = string.charAt(max_length-1);
int index = 0;
if (c != ' ') {
index = string.substring(0, max_length).lastIndexOf(" ");
}
else {
index = max_length-1;
}
// creo la stringa da mostrare
string = string.substring(0, index)+"\n"+string.substring(index+1);
super.insertString(offset, string, attr);
}
}
public LineWrapTest(int max_length, String text) {
super("Test Document");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ta = new JTextArea(new MyDocument(max_length));
ta.setText(text);
ta.setFont(new java.awt.Font("Courier New", java.awt.Font.PLAIN, 14));
ta.setEditable(false);
this.getContentPane().add(ta);
this.setVisible(true);
this.pack();
}
public static void main (String[] args) {
new LineWrapTest(20, "Testo di Prova, sopra 40 butta via tutto");
}
}
Dovresti vedere solo 2 righe, e nella seconda riga la "o" finale di "tutto" non dovrebbe esserci.