I'm trying to undo the setText() method effect in a JEditorPane. Here is my code:
public final class UndoManagerTestForJEditorPane {
private final JEditorPane editor = new JEditorPane();
private final UndoManager undoManager = new UndoManager();
public JComponent makeUI() {
editor.setContentType("text/html");
HTMLDocument document = (HTMLDocument) editor.getDocument();
document.addUndoableEditListener(undoManager);
editor.setText("Hello");
JPanel p = new JPanel();
p.add(new JButton(new AbstractAction("undo") {
@Override
public void actionPerformed(ActionEvent e) {
if (undoManager.canUndo()) {
undoManager.undo();
}
}
}));
p.add(new JButton(new AbstractAction("redo") {
@Override
public void actionPerformed(ActionEvent e) {
if (undoManager.canRedo()) {
undoManager.redo();
}
}
}));
p.add(new JButton(new AbstractAction("setText(new Date())") {
@Override
public void actionPerformed(ActionEvent e) {
String str = new Date().toString();
editor.setText(str);
}
}));
Box box = Box.createVerticalBox();
box.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
box.add(makePanel("Default", editor));
JPanel pp = new JPanel(new BorderLayout());
pp.add(box, BorderLayout.NORTH);
pp.add(p, BorderLayout.SOUTH);
return pp;
}
private static JPanel makePanel(String title, JComponent c) {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createTitledBorder(title));
p.add(c);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new UndoManagerTestForJEditorPane().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
The default behaviour is done with four steps:
1) Nothing is done, the cursor doesn't even move..
2) The cursor gets down with almost 10 lines under the inserted word..
3) The text get disappeared..
4) the old text appears finally..
So, instead of these steps, could we do it just only with one undo step like in this link for JTextField JTextArea setText() & UndoManager, but with JEditorPane ?
The problem the replace method for JEditorPane does not get executed when setText() is called on JEditorPane...
Please any help ?
Thank you