簡體   English   中英

如何讓JEditorPane在JTextArea中顯示文本?

[英]How to get JEditorPane to display text as in JTextArea?

我想讓JEditorPane像在JTextArea一樣顯示文本。 使用JEditorPane的原因是我想在特定的文本模式(帶有a href )上創建鏈接。 我研究了JTextPane但沒有找到簡單的方法。 文本將被填充,因此填充和保留正確的空格數很重要。 顯示之間的差異如下所示: 在此處輸入圖片說明

我希望JEditorPane以與JTextArea (在左側)完全相同的方式顯示文本。 也許,還有另一種更好的方法呢? 當我正確顯示文本時,某些文本(如1233將具有鏈接,並且關聯的事件偵聽器將被觸發。

編碼:

import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;

public class Test {
    public static void main(String[] args)throws Exception {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }

    final static String sampleText=
            "\n" +
                    "    1233 2001/16/07       This is test\n" +
                    "                          With padding\n" +
                    "                               more padding\n" +
                    "                               and more padding";

    private static void createAndShowGUI() {
        final JFrame frame = new JFrame("test");
        //final JTextComponent textComponent=new JTextArea();
        final JEditorPane textComponent=new JEditorPane();
        textComponent.setContentType("text/html");
        textComponent.setFont(textComponent.getFont().deriveFont(11.5f));// larger font
        textComponent.setText(sampleText);
        frame.getContentPane().add(textComponent);
        frame.setPreferredSize(new Dimension(370,120));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.pack();
        frame.setVisible(true);
    }
}

使用純文本時,這可以是一個解決方案:

textComponent.setFont(new JTextArea().getFont().deriveFont(11.5f));

但格式丟失。 因此,當我將contentType設置為“ text / html”時,這不起作用。 當我設置內容類型(甚至使用Monospaced字體)時,將使用JEditorPane

在此處輸入圖片說明

解決方案是,無論是什么textComponentJTextAreaJEditorPane ):

    textComponent.setFont(new JTextArea().getFont().deriveFont(11.5f));

這將強制JEditorPane使用與JTextArea相同的字體。 此外,將空格替換為html實體,將換行符替換為<br>

    sampleText=sampleText.replaceAll("\n","<br>").replaceAll("\\s","&nbsp;");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM