我正在使用JEditorPane
构建HTML编辑器,但是我遇到了一些与Foreground Actions不一致的性能问题。我的编辑器的简化版本有三个动作:将字体颜色更改为红色或蓝色,或更改字体大小。现在使用以下testFile.html文件:
<html>
<head><title>Title</title></head>
<body link="#0000FF" bgcolor="white">
<font size="4" face="arial" color="black">Some test text</font>
<font size="3" face="arial" color="black">Some new test text </font>
</body>
</html>
有时我可以在编辑器中突出显示某些文字,然后按红色或蓝色按钮,它可以正常工作,即它会改变颜色。在其他情况下(即如果我关闭我的JVM并再次启动它)颜色将不会改变直到我在同一文本上应用StyledEditorKit.FontSizeAction
。
我是如何应用ForegroundActions
的?或者这可能是一些Java bug?
以下代码:
public class EditorTest extends JFrame{
private JEditorPane editorPane;
public EditorTest()
{
editorPane = new JEditorPane();
editorPane.setContentType("text/HTML");
getContentPane().add(editorPane, BorderLayout.CENTER);
editorPane.setEditorKit(new HTMLEditorKit());
Action a = new StyledEditorKit.ForegroundAction("RedColor", Color.RED);
editorPane.getActionMap().put("RedColor", a);
JToolBar bar = new JToolBar();
JButton button = new JButton("blue");
button.addActionListener(new StyledEditorKit.ForegroundAction (
"set-foreground-red", Color.blue));
bar.add(editorPane.getActionMap().get("font-size-12")).setText("12");
bar.add(button);
bar.add(editorPane.getActionMap().get("RedColor")).setText("Red");
getContentPane().add(bar, BorderLayout.NORTH);
setSize(650,600);
setVisible(true);
File file = new File("testFile.html");
FileReader reader = null;
try
{
reader = new FileReader(file);
editorPane.read(reader, null);
}
catch (IOException ex){}
}
}
答案 0 :(得分:7)
使用下面的sscce,我无法再现您描述的效果。如果未在event dispatch thread上构造和操作仅,则可能会出现此类异常。该示例相应地使用EventQueue.invokeLater()
。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JToolBar;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.html.HTMLEditorKit;
/** http://stackoverflow.com/questions/8523445 */
public class StyledEditorTest extends JFrame {
public StyledEditorTest() {
JEditorPane editorPane = new JEditorPane();
editorPane.setContentType("text/HTML");
editorPane.setEditorKit(new HTMLEditorKit());
editorPane.setText("<hr>Welcome to <b>StackOverFlow!</b><hr>");
JToolBar bar = new JToolBar();
bar.add(new StyledEditorKit.ForegroundAction("Red", Color.red));
bar.add(new StyledEditorKit.ForegroundAction("Blue", Color.blue));
bar.add(new StyledEditorKit.FontSizeAction("12", 12));
bar.add(new StyledEditorKit.FontSizeAction("14", 14));
bar.add(new StyledEditorKit.FontSizeAction("16", 16));
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.add(bar, BorderLayout.NORTH);
this.add(editorPane, BorderLayout.CENTER);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new StyledEditorTest();
}
});
}
}