java - JEditorPane 内容类型“text/html”换行符,不创建段落
问题描述
当我创建一个JEditorPane
withsetContentType("text/html")
并按 Enter 编辑文本时,<p style="margin-top: 0">
会创建一个新的 html 段落 ( )。有没有办法插入换行符(<br>
)而不是那个?
这是示例:
import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setTitle("Text Area");
JEditorPane editor = new JEditorPane();
editor.setContentType("text/html");
Box pane = Box.createVerticalBox();
pane.add(editor);
frame.add(pane);
frame.setSize(500, 500);
frame.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
System.out.println(editor.getText());
e.getWindow().dispose();
}
});
frame.setVisible(true);
}
}
这是书面文本的输出:
<html>
<head>
</head>
<body>
<p style="margin-top: 0">
First line
</p>
<p style="margin-top: 0">
This is a new line
</p>
</body>
</html>
这就是我想要的:
<html>
<head>
</head>
<body>
<p style="margin-top: 0">
First line<br>
This is a new line
</p>
</body>
</html>
解决方案
我可以解决它,为组合键创建一个新动作Shift + Enter
:
private static final String NEW_LINE = "new-line";
private static void initializeEditorPane(JEditorPane textArea) {
HTMLEditorKit kit = new HTMLEditorKit();
textArea.setEditorKit(kit);
InputMap input = textArea.getInputMap();
KeyStroke shiftEnter = KeyStroke.getKeyStroke("shift ENTER");
input.put(shiftEnter, NEW_LINE);
ActionMap actions = textArea.getActionMap();
actions.put(NEW_LINE, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
try {
kit.insertHTML((HTMLDocument)textArea.getDocument(), textArea.getCaretPosition(),
"<br>", 0,0, HTML.Tag.BR);
textArea.setCaretPosition(textArea.getCaretPosition()); // This moves caret to next line
} catch (BadLocationException | IOException ex) {
ex.printStackTrace();
}
}
});
}
推荐阅读
- javascript - 在 Javascript 中发布和访问 URL
- azure - 将 Azure Functions 与 Python 结合使用时的文件事务数量非常多
- sendmail - mailx和sendmail的区别?
- java - JSTL Spring MVC 递归表单 JSP
- scala - Scala:返回一个参数化的实例
- css - 仅通过 CSS 固定页脚
- python - Python:神经网络 - TypeError:“历史”对象不可下标
- python-3.x - 为什么我在找到并打印 URL 之后得到一个 KeyError?
- wordpress - WooCommerce 产品类别说明
- python - 加载图像时出现 Errno 22