Best way to limit max number of characters per line in JEditorPane ?
Hi,
I need to write swing based editor using which allows the user to
write a plain text document, which has a fixed maximum column width.
The column width will be supplied by the model class later. I finally
managed to write one using a document filter, as shown below. My
question is this the best (or a reasonable) way to realize this or are
there better options / solutions / ideas ?
Any comments are welcome.
[code]
public class LMEditor extends JFrame {
private int frameWidth = 600 ;
private int frameHeight = 400 ;
private JEditorPane motivationTxtEdt = null ;
private static final int MAXCOLUMNS = 30 ;
public LMEditor(){
super() ;
initialize() ;
}
public void initialize() {
// Init frame
setDefaultCloseOperation(EXIT_ON_CLOSE) ;
this.setSize(frameWidth,frameHeight) ;
.... irrelevant code ...
motivationTxtEdt = new JEditorPane() ;
motivationTxtEdt.setBounds(20,120,400,300) ;
motivationTxtEdt.setContentType("text/plain") ;
Document motivationDoc = motivationTxtEdt.getDocument();
DocumentFilter motivationFilter = new
ColumnWidthDocumentFilter(MAXCOLUMNS,motivationTxtEdt);
((AbstractDocument) motivationDoc).setDocumentFilter
(motivationFilter);
LMEditorPanel.add(motivationTxtEdt) ;
setVisible(true) ;
}
class ColumnWidthDocumentFilter extends DocumentFilter {
int maxColumnWidth = 0 ;
JEditorPane motivationEditorPane = null ;
public ColumnWidthDocumentFilter(int maxColumnWidth, JEditorPane
motivationEditorPane) {
this.maxColumnWidth = maxColumnWidth ;
this.motivationEditorPane = motivationEditorPane ;
}
public void insertString(DocumentFilter.FilterBypass fb, int offset,
String string,
AttributeSet attr) throws BadLocationException {
super.insertString(fb, offset, string, attr);
}
public void remove(DocumentFilter.FilterBypass fb, int offset, int
length)
throws BadLocationException {
super.remove(fb, offset, length);
}
public void replace(DocumentFilter.FilterBypass fb, int offset, int
length, String text,
AttributeSet attrs) throws BadLocationException {
// Get the caret position
int caretPosition = motivationEditorPane.getCaretPosition() ;
// Get line and linestart of root Document
Element root = fb.getDocument().getDefaultRootElement() ;
int line = root.getElementIndex( caretPosition );
int lineStart = root.getElement( line ).getStartOffset();
if (((caretPosition - lineStart + 1) < this.maxColumnWidth) ||
(text == "\n")) {
super.replace(fb, offset, length, text, attrs);
}
}
}