【问题标题】:Java - Highlighting Text Between two Chars - JTextPaneJava - 突出显示两个字符之间的文本 - JTextPane
【发布时间】:2013-03-31 08:51:46
【问题描述】:

我需要能够突出显示两个字符内的单词。例如:

//Highlight whatever is in between the two quotation marks
String keyChars = " \" \" ";

我已经为此苦苦挣扎了好几个星期了。我查过它,读过源代码,写过代码,但我还没有弄清楚我是如何做到这一点的。

【问题讨论】:

  • "wrote code," 您具体尝试了什么?它是如何失败的?
  • 查看this 示例,它使用JEditorPane 但概念应该相同
  • 这是一个提示尝试搜索 DefaultHighlighter.DefaultHighlightPainter 类。并检查什么是正则表达式。
  • 我猜这与他的另一个问题 (stackoverflow.com/questions/15867900/…) 有关,他试图通过玩 AttributeSets 来进行语法突出显示。我也猜测他正在寻找一种算法来查找包含转义引号的引用文字。
  • 抱歉回复晚了。在回答 camickr 时,这与那个问题并没有真正的关系。在我问链接中的问题之前,我没有突出显示的引号。这么说,感谢到目前为止的所有回复!

标签: java swing highlighting jtextpane


【解决方案1】:

以下代码 sn -p 有效。

ed=new JEditorPane();
ed.setText("This \"text\" contains \"quotes\". The \"contents\" of which are highlighted");
Pattern pl;
pl=Pattern.compile("\"");
Matcher matcher = pl.matcher(ed.getText());
int end=0,beg=0;
while(matcher.find())
{
    beg=matcher.start();
    matcher.find(); //finding the next quote
    end=matcher.start();
    DefaultHighlightPainter d =  new DefaultHighlightPainter(Color.YELLOW);
    try {
        ed.getHighlighter().addHighlight(beg+1, end,d);
    } catch (BadLocationException ex) {
        ex.printStackTrace();
    }
}

【讨论】:

  • 感谢您的回复,但不幸的是,这不是我想要的——我的错,因为我的问题不够清楚。我应该说的是两个角色之间的“实时突出显示”。我的错。
猜你喜欢
  • 1970-01-01
  • 2011-08-06
  • 1970-01-01
  • 2015-01-24
  • 1970-01-01
  • 2022-12-07
  • 2019-02-19
  • 2014-05-02
  • 1970-01-01
相关资源
最近更新 更多