javascript - JTEXTPANE 多彩前景设置

标签 javascript java css eclipse swing

我在 JFrame 中有 JTextPane,我可以在其中键入 SQL 查询,在键入时我想以我自己定义的字体颜色显示不同的关键字文本,该字体颜色必须动态显示。

例如:如果我输入如下

SELECT * FROM TABLE WHERE 1=1;

我需要为每个关键字使用不同的颜色,这些颜色必须在我输入时在 JTextPane 中动态更新。就像下面这样

SELECT --> red color
FROM --> white color
WHERE --> green color

请提供简单的解决方案来实现我的上述场景,提前致谢

最佳答案

不是最佳的,但我想出了一个解决方案,首先从 Pane 中删除整个文本,然后替换它,遍历每个单词并使用 StyleContextAttributeSet如果单词与 HashMap 中的某个字符串匹配,则更改颜色。

输出:

enter image description here

代码:

import java.awt.Color;
import java.awt.EventQueue;
import java.util.HashMap;

import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

public class Example {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Example();
            }
        });
    }

    public Example() {

        JFrame frame = new JFrame();

        MyTextPane textPane = new MyTextPane();
        textPane.getColoredWordsMap().put("SELECT", Color.RED);
        textPane.getColoredWordsMap().put("FROM", Color.WHITE);
        textPane.getColoredWordsMap().put("WHERE", Color.GREEN);

        frame.getContentPane().add(textPane);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }

    private class MyTextPane extends JTextPane {

        private boolean human = true;
        private HashMap<String, Color> coloredWordsMap = new HashMap<String, Color>();

        public MyTextPane() {
            setBackground(Color.GRAY);
            getDocument().addDocumentListener(new DocumentListener() {
                @Override
                public void changedUpdate(DocumentEvent e) {
                    updateText();
                }

                @Override
                public void insertUpdate(DocumentEvent e) {
                    updateText();
                }

                @Override
                public void removeUpdate(DocumentEvent e) {
                    updateText();
                }
            });
        }

        private void updateText() {
            if (human) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        human = false;
                        JTextPane textPane = MyTextPane.this;
                        boolean spaceBar = false;
                        if (textPane.getText().length() > 0
                                && textPane.getText().substring(textPane.getText().length() - 1).equals(" ")) {
                            spaceBar = true;
                        }
                        String[] words = textPane.getText().split(" ");
                        textPane.setText("");
                        for (String word : words) {
                            // This is not a mistake. The .equals method would
                            // just compare the content of the strings.
                            String toAppend = (words[words.length - 1] == (word)) ? "" : " ";
                            boolean colored = false;
                            for (String coloredWord : getColoredWordsMap().keySet()) {
                                if (word.equals(coloredWord)) {
                                    append(word + toAppend, getColoredWordsMap().get(coloredWord));
                                    colored = true;
                                }
                            }
                            if (!colored) {
                                append(word + toAppend, Color.BLACK);
                            }
                        }
                        if (spaceBar) {
                            append(" ", Color.BLACK);
                        }
                        human = true;
                    }
                });
            }
        }

        private void append(String text, Color color) {
            JTextPane textPane = MyTextPane.this;
            StyleContext sc = StyleContext.getDefaultStyleContext();
            AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, color);
            int length = textPane.getDocument().getLength();
            textPane.setCaretPosition(length);
            textPane.setCharacterAttributes(aset, false);
            textPane.replaceSelection(text);
        }

        public HashMap<String, Color> getColoredWordsMap() {
            return coloredWordsMap;
        }

    }

}

关于javascript - JTEXTPANE 多彩前景设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33959403/

相关文章:

javascript - 无法获取图像的宽度

javascript - 将对象从 NodeJS 传递到客户端,然后传递到 KnockoutJS View 模型

javascript - 在 JavaScript 中计算文件的 SHA-256 哈希值和 B64

javascript - "if (!' '.replace(/^/, String))"是做什么的?

java - 有没有办法可以更改 Android 应用程序的向后兼容性?

html - 仅 CSS 技术,用于具有可变高度、无表格、无重叠的固定底部页脚

java - 如何在Java中通过用户输入搜索特定列?

java - Cucumber Java with Selenium - 重用登录功能并将其与其他功能连接起来

javascript - Flexslider - 固定图片充电

jquery - 当周围的 css 不允许你时,如何在 ul li div 中弹出图像