如何突出显示jtable中的多个单元格 [英] how to highlight multiple cells in jtable

查看:67
本文介绍了如何突出显示jtable中的多个单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在jtable数据中搜索文本. 例如"ADMIN"文本在jtable中出现多个位置,然后如何突出显示 所有包含指定值的单元格.

I have to search text in jtable data. e.g. "ADMIN" text is appearing multiple places in jtable then how to highlight all the cells that contains specified value.

有人有什么主意吗?

推荐答案

按照@kleopatra的建议,使用自定义CellRenderer(以下示例仅是POC,添加了用于更改搜索模式,突出显示颜色等的方法. ):

As @kleopatra suggested, use a custom CellRenderer (the following example is just a POC, add methods to change the search pattern, highlight color, etc.):

import java.awt.Color;
import java.awt.Component;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

public class CellHighlighter {

    private static class CellHighlighterRenderer extends JLabel implements TableCellRenderer {

        public CellHighlighterRenderer() {
            setOpaque(true); // Or color won't be displayed!
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            String val = (String)value;
            Color c;
            if (val.matches(".*MIN.*")) // Add a method to configure the regexpr
                c = Color.YELLOW; // Add a method to configure color
            else
                c = UIManager.getColor("Table.background");
            setBackground(c);
            setText(val);
            return this;
        }
    }

    public static void main(String[] args) {
        String[] columnNames = {
            "Login", "Real name", "Age", "Birthday"
        };
        String[][] data = {
            {"toto", "Toto Mackwert", "73", "18/06/1940"},
            {"adm", "ADMINISTRATOR", "13", "01/01/2000"},
            {"AMINA", "Amina Farou", "3", "01/01/2010"},
        };
        JTable table = new JTable(data, columnNames);
        table.setDefaultRenderer(Object.class, new CellHighlighterRenderer());
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(scrollPane);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

}

这篇关于如何突出显示jtable中的多个单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆