JTable颜色行和单元格动态

时间:2013-03-13 12:18:22

标签: java swing jtable tablecellrenderer

我想为JTable对象创建搜索功能。 我有一个JTextFiled,我把我的文本搜索。 我想更改包含此文本的颜色行和单元格。 现在我被卡住了,因为我不知道如何动态改变颜色。

public class TableSearchCellRenderer extends DefaultTableCellRenderer {
    String search = "";

    public void setSearch(String search) {
        this.search = search;
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        if (table.getValueAt(row, column).equals(search)) {
            setBackground(Color.green);
        }
        return this;
    }
}

我尝试过类似的东西,但它不起作用。

我试图像这样调用rerender表

 String selectedTitle = tabbed.getTitleAt(tabbed.getSelectedIndex());
 JTable table = tabels.get(selectedTitle);

 ((TableSearchCellRenderer)table.getDefaultRenderer(String.class)).setSearch(searchField.getText());
 table.repaint();
 ((AbstractTableModel) table.getModel()).fireTableDataChanged();

但没有成功:(

你能帮帮我吗?

3 个答案:

答案 0 :(得分:3)

以下是基于TableCellRenderer的搜索功能的工作版本。您可能遇到的问题之一是,尽管您的TableModel包含String,但如果您使用DefaultTableModel,则它始终会返回Object.class所有数据,因此JTable将使用DefaultTableCellRenderer而不是TableSearchCellRenderer

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.util.Random;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

public class TestTable2 {

    private String search;

    public String getSearch() {
        return search;
    }

    public void setSearch(String search) {
        this.search = search;
    }

    private class TableSearchRenderer extends DefaultTableCellRenderer {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            setBackground(null);
            Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (getSearch() != null && getSearch().length() > 0 && value.toString().contains(getSearch())) {
                setBackground(Color.RED);
            }
            return tableCellRendererComponent;
        }
    }

    protected void initUI() {
        DefaultTableModel model = new DefaultTableModel();
        for (int i = 0; i < 5; i++) {
            model.addColumn("Column " + (i + 1));
        }
        Random random = new Random();
        for (int i = 0; i < 200; i++) {
            Vector<Object> row = new Vector<Object>();
            for (int j = 0; j < 40; j++) {
                row.add(WORDS[random.nextInt(WORDS.length)]);
            }
            model.addRow(row);
        }
        table = new JTable(model);
        TableSearchRenderer renderer = new TableSearchRenderer();
        table.setDefaultRenderer(Object.class, renderer);
        textField = new JTextField(30);
        textField.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void removeUpdate(DocumentEvent e) {
                updateSearch();
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                updateSearch();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                updateSearch();
            }
        });
        JFrame frame = new JFrame(TestTable2.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JScrollPane scrollpane = new JScrollPane(table);
        scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        frame.add(scrollpane, BorderLayout.CENTER);
        frame.add(textField, BorderLayout.NORTH);
        frame.setSize(1000, 800);
        frame.setVisible(true);
    }

    protected void updateSearch() {
        setSearch(textField.getText());
        table.repaint();
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
            UnsupportedLookAndFeelException {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestTable2().initUI();
            }
        });
    }

    private static final String[] WORDS = { "art", "australia", "baby", "beach", "birthday", "blue", "bw", "california", "canada", "canon",
            "cat", "chicago", "china", "christmas", "city", "dog", "england", "europe", "family", "festival", "flower", "flowers", "food",
            "france", "friends", "fun", "germany", "holiday", "india", "italy", "japan", "london", "me", "mexico", "music", "nature",
            "new", "newyork", "night", "nikon", "nyc", "paris", "park", "party", "people", "portrait", "sanfrancisco", "sky", "snow",
            "spain", "summer", "sunset", "taiwan", "tokyo", "travel", "trip", "uk", "usa", "vacation", "water", "wedding" };
    private JTable table;
    private JTextField textField;

}

答案 1 :(得分:1)

Table Row Rendering。该示例对固定字进行行级突出显示。您需要修改代码才能在搜索词上突出显示。

另一种方法是过滤表格以仅查看包含您要搜索的文本的行。有关工作示例,请参阅Sorting and Filtering

答案 2 :(得分:0)

有效。我改变了准备渲染器。

JTable table = new JTable() {
                private static final long serialVersionUID = 1L;

                public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                    Component c = super.prepareRenderer(renderer, row, column);

                    **if (column == 0) {
                        for (int i = 0; i < getModel().getColumnCount(); i++) {
                            if (((TableSearchRenderer) getDefaultRenderer(String.class)).getSearch().length() > 0 && ((TableSearchRenderer) getDefaultRenderer(String.class)).getSearch().toLowerCase().equals(getModel().getValueAt(row, i).toString().toLowerCase()))
                                ((TableSearchRenderer) getDefaultRenderer(String.class)).getRows().add(row);
                        }
                    }**

                    if (((TableSearchRenderer) getDefaultRenderer(String.class)).getRows().contains(row) && c.getBackground() != Color.RED) {
                        c.setBackground(Color.GREEN);
                    }

                    return c;
                }
            };