Java高亮显示被选中文本:StyledDocument.setCharacterAttributes()

Java高亮显示被选中文本:StyledDocument.setCharacterAttributes()
复用代码
javax.swing.text.JTextComponent。requestFocus();
javax.swing.text.JTextComponent。select(start, end);
不获得焦点,文本被选中但不会高亮。
-----------------------
hxzon:上面的方式转移了焦点,更好的方式如下:
JTextPane hexPane;
SimpleAttributeSet notSelected;
SimpleAttributeSet selected;
StyledDocument doc;
//设置样式
notSelected = new SimpleAttributeSet();
        selected = new SimpleAttributeSet(notSelected);
        StyleConstants.setForeground(selected, new DefaultTreeCellRenderer().getTextSelectionColor());
        StyleConstants.setBackground(selected, new DefaultTreeCellRenderer().getBackgroundSelectionColor());
//文本内容
hexPane.setText(packet.messageToHex());
//高亮显示被选中文本
goosetree.addTreeSelectionListener(new TreeSelectionListener() {
   public void valueChanged(TreeSelectionEvent e) {
    TreePath treePath = e.getPath();
    if (treePath == null) {
     return;
    }
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath
      .getLastPathComponent();
    int offset = 0;
                int len = 0;
    if (node.getUserObject() instanceof PropertyNode) {
     PropertyNode leaf = (PropertyNode) node.getUserObject();
     offset = leaf.offset;
     len = leaf.len;
    }
    else if (node.getUserObject() instanceof GooseNode) {
                    GooseNode leaf = (GooseNode) node.getUserObject();
                    offset = leaf.offset;
                    len = leaf.len;
                }
    else if (node.getUserObject() instanceof DatasetNode) {
                    DatasetNode leaf = (DatasetNode) node.getUserObject();
                    offset = leaf.offset;
                    len = leaf.len;
                }
                int end = offset + len;
                offset = offset * 2 + offset;
                end = end * 2 + end;
                offset += offset / 48;
                end += end / 48 - 1;
//                hexPane.requestFocus();
                doc=hexPane.getStyledDocument();
                doc.setCharacterAttributes(0, doc.getLength(), notSelected, true);
                doc.setCharacterAttributes(offset, end - offset, selected, true);
                hexPane.select(offset, end);//加上此句,当选中文本不可见时滚动条自动滚动
   }
});

你可能感兴趣的:(JAVA)