我编写了一个示例应用程序,它由一个JTextPane
和一个打印出文本窗格内容的按钮组成。文本窗格的内容类型设置为“text/html”。
当我输入一些文本并将其打印到控制台时,文本会自动换行。
例如,给定以下输入:
Watercress shallot radish chickweed bitterleaf bush tomato salad garlic beet greens black-eyed pea green bean salsify bell pepper. Catsear celery green bean broccoli rabe spring onion tatsoi prairie turnip wattle seed cucumber burdock. Chickweed cucumber chickpea bush tomato wakame taro fava bean arugula catsear azuki bean.
输出是这样的
Watercress shallot radish chickweed bitterleaf bush tomato salad garlic
beet greens black-eyed pea green bean salsify bell pepper. Catsear celery
green bean broccoli rabe spring onion tatsoi prairie turnip wattle seed
cucumber burdock. Chickweed cucumber chickpea bush tomato wakame taro fava
bean arugula catsear azuki bean.
有没有办法保留输入文本的格式?我打算将输入存储在数据库中,因此我将换行符替换为<br>
,但文本窗格会自动插入自己的换行符。
如果有其他解决方案,我也可以尝试,但在大多数情况下,我希望能够显示 HTML,同时允许用户修改输入。
这是示例的代码。您应该能够编译并运行它。
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
public class TextPaneTest extends JFrame {
private JTextPane textPane = null;
public static void main(String args[]) {
new TextPaneTest();
}
public TextPaneTest() {
// Main panel
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
// Panel holding text
JPanel textPanel = new JPanel();
textPanel.setLayout(new BorderLayout());
// Text pane
textPane = new JTextPane();
textPane.setContentType("text/html");
// Button
JButton button = new JButton();
button.setText("Print Text");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String text = textPane.getText();
text = text.substring(text.indexOf("<body>") + 6, text.indexOf("</body>"));
System.out.println(text);
}
});
textPanel.add(textPane);
panel.add(textPanel, BorderLayout.CENTER);
panel.add(button, BorderLayout.SOUTH);
// Add everything to the frame
this.add(panel);
this.setSize(1000, 500);
setVisible(true);
}
}