Java Swing : Jtable 仅突出显示单元格中单词的一部分

Java Swing : Jtable Highlight ONLY part of a word in a cell

您好,这个问题很具体。对于 class,我们必须制作某种图书馆程序。

我将我的列表显示在 JTable 中,并且我实现了一个搜索 window,它也使用了 JTable...我制作了一个自定义 CellRenderer,以便在书的代码中包含术语搜索时突出显示或标题。

我的问题是现在它把整个单词都加粗了....是否可以只加粗该单词的一部分?

现在我还有一个 class 函数,它为我提供了单元格值中搜索词开始和结束的索引。 (在 getSearchIndex(Object, String) 下的 class 末尾找到)

这是一个屏幕,在渲染器代码下方(颜色代码是分开的)。

import java.awt.Component;
import java.awt.Font;

import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

 class HighlightRenderer extends DefaultTableCellRenderer {

private static final long serialVersionUID = 1L;
String searched = "";

public HighlightRenderer(String search){
    super();

    if(search != null && search != "")
        searched = search;
    else searched = "";
}

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){
    Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

        if(searched.length() == 0){
            cellComponent.setFont(new Font(this.getFont().getName(), Font.PLAIN, this.getFont().getSize()));
        }

        else if(value.toString().toUpperCase().contains(searched.toUpperCase())){
            cellComponent.setFont(new Font(this.getFont().getFontName(), Font.BOLD, this.getFont().getSize()));
            int[] index = getSearchIndex(value, searched);
        }

    return cellComponent;
}

private int[] getSearchIndex(Object value, String search){

    int searchLength = search.length();
    String key = (String) value;

    int[] retour = new int[2];
    retour[0] = -1;
    retour[1] = -1;

    for(int i = 0; i < key.length(); i++){
        if(key.substring(i, i+searchLength).equalsIgnoreCase(search)){
            retour[0] = i;
            retour[1] = i + searchLength;
            return retour;
        }
    }
    return retour;

}

}

提前感谢您提供任何提示或技巧。

文本组件可以有一个 StyledDocument 并有部分文本通过指定的颜色属性进行标记。

使用 HTML 更便宜一些。任何文本组件,例如单元格渲染器默认提供的 JLabel。 HTML 可能很偏。

JLabel label = (JLabel) cellComponent; // Or new JLabel();
label.setText(
    "<html>An <span style='background-color: lightskyblue'>example</span> of HTML");

String highlight(String text, String sought) {
     text = StringEscapeUtils.escapeHTML4(text); // <, >
     sought = StringEscapeUtils.escapeHTML4(sought);
     return "<html>" + text.replace(sought, "<b>" + sought + "</b>");
}