1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| public class JEditorPaneDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box editorPanel = new Box(BoxLayout.PAGE_AXIS);
JEditorPane editor = new JEditorPane();
editorPanel.add(editor);
editorPanel.add(Box.createVerticalStrut(100));
editor.setText(createText());
JScrollPane scrollpane = new JScrollPane(editorPanel,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollpane.getViewport().setBackground(editor.getBackground());
editor.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent event) {
try {
if ( !scrollToEnd(scrollpane, editor, event.getDot()) ) {
scrollToEnd(scrollpane, editor, event.getMark());
}
} catch (BadLocationException e) {
}
}
});
editor.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
}
@Override
public void insertUpdate(DocumentEvent e) {
update();
}
@Override
public void changedUpdate(DocumentEvent e) {
update();
}
private void update() {
try {
scrollToEnd(scrollpane, editor, editor.getCaret().getDot());
} catch (BadLocationException e) {
}
}
});
frame.add(scrollpane);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
protected static int lineCount(JEditorPane editor) {
int totalCharacters = editor.getText().length();
return lineCount(editor, totalCharacters);
}
protected static int lineCount(JEditorPane editor, int offset) {
int totalCharacters = editor.getText().length();
int lineCount = (totalCharacters == 0) ? 1 : 0;
try {
while (offset > 0) {
offset = javax.swing.text.Utilities.getRowStart(editor, offset) - 1;
lineCount++;
}
} catch (BadLocationException e) {
}
return lineCount;
}
protected static boolean scrollToEnd(JScrollPane scrollpane, JEditorPane editor, int pos) throws BadLocationException {
int last=lineCount(editor);
if ( last==0 ) return false;
int current=lineCount(editor, pos);
if ( current==last) {
SwingUtilities.invokeLater(()->
scrollpane.getVerticalScrollBar().getModel().setValue(scrollpane.getVerticalScrollBar().getModel().getMaximum()));
return true;
}
return false;
}
private static String createText() {
StringBuilder sb=new StringBuilder("1 ");
int n=2;
for(int i=0;i<300; i++) {
if ( i>0 && i%ThreadLocalRandom.current().nextInt(3, 7)==0 ) {
sb.append("\n"+n+" ");
n++;
}
else if ( sb.length()!=0) {
sb.append(" ");
}
sb.append("blah");
}
return sb.toString();
}
} |
Partager