【发布时间】:2014-11-17 22:57:36
【问题描述】:
我正在尝试撤消 JEditorPane 中的 setText() 方法效果。这是我的代码:
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);
}
}
默认行为通过四个步骤完成:
1) 什么都没做,光标甚至没有移动..
2) 光标下降到插入的单词下将近 10 行..
3) 文字消失了..
4) 旧文本终于出现了..
那么,除了这些步骤,我们是否可以只使用一个撤消步骤(如 JTextField JTextArea setText() & UndoManager 的此链接中的一个撤消步骤,但使用 JEditorPane 呢?
在JEditorPane上调用setText()时,JEditorPane的replace方法没有被执行的问题...
请帮忙?
谢谢
【问题讨论】:
-
感谢您的回答,但我已经在使用这种方法,问题就出在使用例如:JEditorPane ed = new JEditorPane(); ed.setText("一些文字");当我撤消时,行为如第一篇文章中所述。有什么帮助吗?
-
那么你最好提供一个runnable example 来证明你的问题。这将导致更少的混乱和更好的响应
-
我添加了代码作为演示,非常感谢:)