9

私はこれをしばらく探していましたが、これまでに思いついたのは、スタイルを作成して次のようなキャラクターに適用する方法だけです。

StyledDocument doc = (StyledDocument) new DefaultStyledDocument();
JTextPane textpane = new JTextPane(doc);
textpane.setText("Test");
javax.swing.text.Style style = textpane.addStyle("Red", null);
StyleConstants.setForeground(style, Color.RED);
doc.setCharacterAttributes(0, 1, textpane.getStyle("Red"), true); 

これは、ドキュメントにスタイルが数個しかなく、後で簡単に適用できるように名前で保存する場合に便利です。私のアプリケーションでは、テキスト内のすべての文字に対して、前景色(数少ない値の1つ)と背景色(グレースケール、多くの異なる値)を個別に設定できるようにしたいと考えています。このために潜在的に数百/数千の異なるスタイルを作成することは大きな無駄のようです。毎回新しいスタイルを作成せずにこれらの属性を設定する方法はありますか?テキストをレンダリングするだけでよいのであれば、はるかに簡単ですが、編集可能にする必要もあります。でこれを行う方法はありますJTextPaneか、またはこの機能を提供する別のスイングクラスがありますか?

4

3 に答える 3

14

テキストペインの各文字のスタイルを変更する場合は、これを完全にランダムに行う方法があります。文字ごとに異なる属性セットを作成します。適切な組み合わせを見つけるのはあなた次第です(前景/背景のコントラスト、文字のサイズにあまり違いがないなど)。同じスタイルを2回使用しないように、すでに適用したさまざまなスタイルを保存することもできます。

ここに画像の説明を入力してください

import java.awt.Color;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class TestDifferentStyles {
    private void initUI() {
        JFrame frame = new JFrame(TestDifferentStyles.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        StyledDocument doc = new DefaultStyledDocument();
        JTextPane textPane = new JTextPane(doc);
        textPane.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has "
                + "been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of "
                + "type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the "
                + "leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the"
                + " release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing "
                + "software like Aldus PageMaker including versions of Lorem Ipsum.");

        Random random = new Random();
        for (int i = 0; i < textPane.getDocument().getLength(); i++) {
            SimpleAttributeSet set = new SimpleAttributeSet();
            // StyleConstants.setBackground(set, new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            StyleConstants.setForeground(set, new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            StyleConstants.setFontSize(set, random.nextInt(12) + 12);
            StyleConstants.setBold(set, random.nextBoolean());
            StyleConstants.setItalic(set, random.nextBoolean());
            StyleConstants.setUnderline(set, random.nextBoolean());

            doc.setCharacterAttributes(i, 1, set, true);
        }

        frame.add(new JScrollPane(textPane));
        frame.setSize(500, 400);
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestDifferentStyles().initUI();
            }
        });
    }

}
于 2012-10-25T21:41:11.063 に答える
9

意味がわかりませんが、ループ内の各文字をループして、JtextPaneそのループ内で強調表示するすべての文字/文字を繰り返し処理することはできません。ifステートメントで文字をチェックし、それにStyle応じて設定します。

これが私が作った例です。デモンストレーションの目的で、文字hwにのみ実装しました。

ここに画像の説明を入力してください

//necessary imports
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class Test {

    /**
     * Default constructor for Test.class
     */
    public Test() {
        initComponents();
    }

    public static void main(String[] args) {

        /**
         * Create GUI and components on Event-Dispatch-Thread
         */
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Test test = new Test();
            }
        });
    }

    /**
     * Initialize GUI and components (including ActionListeners etc)
     */
    private void initComponents() {
        JFrame jFrame = new JFrame();
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        StyledDocument doc = (StyledDocument) new DefaultStyledDocument();
        JTextPane textPane = new JTextPane(doc);
        textPane.setText("Hello, world! :)");

        //create necessary styles for various characters
        javax.swing.text.Style style = textPane.addStyle("Red", null);
        StyleConstants.setForeground(style, Color.RED);
        javax.swing.text.Style style2 = textPane.addStyle("Blue", null);
        StyleConstants.setForeground(style2, Color.BLUE);

        //create array of characters to check for and style
        String[] lettersToEdit = new String[]{"h", "w"};

        //create arraylist to hold each character in textPane
        ArrayList<String> strings = new ArrayList<>();

        //get all text
        String text = textPane.getText();

        //populate arraylist
        for (int i = 0; i < text.length(); i++) {
            strings.add(text.charAt(i) + "");
        }

        //declare variabe to hold position
        int position = 0;

        for (String s1 : strings) {//for each character in the textpane text
            for (String s2 : lettersToEdit) {//for each character in array to check (lettersToEdit)
                if (s2.toLowerCase().equalsIgnoreCase(s1)) {//if there was a match

                    System.out.println("found a match: " + s1);
                    System.out.println("counter: " + position + "/" + (position + 1));

                    //check which chacacter we matched
                    if (s1.equalsIgnoreCase(lettersToEdit[0])) {
                        //set appropriate style
                        doc.setCharacterAttributes(position, 1, textPane.getStyle("Red"), true);
                    }
                    if (s1.equalsIgnoreCase(lettersToEdit[1])) {
                        doc.setCharacterAttributes(position, 1, textPane.getStyle("Blue"), true);
                    }
                }
            }
            //increase position after each character on textPane is parsed
            position++;
        }

        jFrame.add(textPane);
        //pack frame (size JFrame to match preferred sizes of added components and set visible
        jFrame.pack();
        jFrame.setVisible(true);
    }
}
于 2012-10-25T20:22:19.693 に答える
0

これを行うための最善の方法は、ハイライトのあるエディターで、文字を追いかけるのではなく、パターンを使用する場合と同じだと思います。たとえば、次のようになります。

private static HashMap<Pattern, Color> patternColors;
private static String GENERIC_XML_NAME = "[A-Za-z]+[A-Za-z0-9\\-_]*(:[A-Za-z]+[A-Za-z0-9\\-_]+)?";
private static String TAG_PATTERN = "(</?" + GENERIC_XML_NAME + ")";
private static String TAG_END_PATTERN = "(>|/>)";
private static String TAG_ATTRIBUTE_PATTERN = "(" + GENERIC_XML_NAME + ")\\w*\\=";
private static String TAG_ATTRIBUTE_VALUE = "\\w*\\=\\w*(\"[^\"]*\")";
private static String TAG_COMMENT = "(<\\!--[\\w ]*-->)";
private static String TAG_CDATA = "(<\\!\\[CDATA\\[.*\\]\\]>)";

private static final Color COLOR_OCEAN_GREEN = new Color(63, 127, 127);
private static final Color COLOR_WEB_BLUE = new Color(0, 166, 255);
private static final Color COLOR_PINK = new Color(127, 0, 127);

static {
    // NOTE: the order is important!
    patternColors = new LinkedHashMap<Pattern, Color>();
    patternColors.put(Pattern.compile(TAG_PATTERN), Color.BLUE); // COLOR_OCEAN_GREEN | Color.BLUE
    patternColors.put(Pattern.compile(TAG_CDATA), COLOR_WEB_BLUE);
    patternColors.put(Pattern.compile(TAG_ATTRIBUTE_PATTERN), COLOR_PINK);
    patternColors.put(Pattern.compile(TAG_END_PATTERN), COLOR_OCEAN_GREEN);
    patternColors.put(Pattern.compile(TAG_COMMENT), Color.GRAY);
    patternColors.put(Pattern.compile(TAG_ATTRIBUTE_VALUE), COLOR_OCEAN_GREEN); //Color.BLUE | COLOR_OCEAN_GREEN
}




public XmlView(Element element) {

    super(element);

    // Set tabsize to 4 (instead of the default 8).
    getDocument().putProperty(PlainDocument.tabSizeAttribute, 4);
}
于 2013-08-20T20:55:40.790 に答える