[英]JEditorPane content type “text/html” line breaks with no paragraph creation
When I create a JEditorPane
with setContentType("text/html")
and I press enter editing text, a new html paragraph ( <p style="margin-top: 0">
) is created.当我使用
setContentType("text/html")
创建JEditorPane
并按 Enter 编辑文本时,会创建一个新的 html 段落( <p style="margin-top: 0">
)。 Is there any way to insert line break tags ( <br>
) instead of that?有没有办法插入换行标记(
<br>
)而不是那个?
Here is the example:这是示例:
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);
}
}
This is the outpup of a written text:这是书面文本的输出:
<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>
And this is what I would like to have:这就是我想要的:
<html>
<head>
</head>
<body>
<p style="margin-top: 0">
First line<br>
This is a new line
</p>
</body>
</html>
I could solve it creating a new action for Shift + Enter
key combination:我可以解决它为
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();
}
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.