栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

ColorPane-可以抓取不同字符的字符串吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ColorPane-可以抓取不同字符的字符串吗?

可能有很多方法可以做到这一点,但是…

您需要获取从到给定字符位置的

Styledocument
支持的引用
JTextPane
,从给定字符位置开始,您需要检查给定颜色的字符属性,如果是
true
,请继续输入文本字符,否则就完成了。

import java.awt.Color;import javax.swing.JTextPane;import javax.swing.text.BadLocationException;import javax.swing.text.Element;import javax.swing.text.Style;import javax.swing.text.StyleConstants;import javax.swing.text.Styleddocument;public class Srap {    public static void main(String[] args) {        JTextPane textPane = new JTextPane();        Styleddocument doc = textPane.getStyleddocument();        Style style = textPane.addStyle("I'm a Style", null);        StyleConstants.setForeground(style, Color.red);        try { doc.insertString(doc.getLength(), "BLAH ", style);        } catch (BadLocationException ex) {        }        StyleConstants.setForeground(style, Color.blue);        try { doc.insertString(doc.getLength(), "BLEH", style);        } catch (BadLocationException e) {        }        Color color = null;        int startIndex = 0;        do { Element element = doc.getCharacterElement(startIndex); color = doc.getForeground(element.getAttributes()); startIndex++;        } while (!color.equals(Color.RED));        startIndex--;        if (startIndex >= 0) { int endIndex = startIndex; do {     Element element = doc.getCharacterElement(endIndex);     color = doc.getForeground(element.getAttributes());     endIndex++; } while (color.equals(Color.RED)); endIndex--; if (endIndex > startIndex) {     try {         String text = doc.getText(startIndex, endIndex);         System.out.println("Red text = " + text);     } catch (BadLocationException ex) {         ex.printStackTrace();     } } else {     System.out.println("Not Found"); }        } else { System.out.println("Not Found");        }    }}

这个示例简单地找到了第一个红色的单词,但是您可以轻松地遍历整个文档并找到所有想要的单词…



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/507572.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号