如果单元格值相同,则更改JTable中的单元格背景 [英] If a cell value is same, changing a cell background in JTable

查看:155
本文介绍了如果单元格值相同,则更改JTable中的单元格背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于JTable的问题。

I have a question for JTable.

当我选择一个单元格然后在我选择的JTable中有相同的值单元格时,这些单元格突出显示背景红色。

When I select a cell and then there are same value cell in JTable which I chose, that cells highlight background red color.

我不知道该怎么办....

I don't know what to do....

PS:对不起,我做的不知道如何在这里输入代码...... ;;

P.S: I am sorry, I do not know how to enter the code in here...;;

推荐答案

你可以实现 ListSelectionListener 跟踪表格中的选择更改。然后实现 TableCellRenderer ,它将更改具有所选对象的相同值的单元格的背景。查看如何使用表以获取有关<$的更多详细信息c $ c> JTable ,渲染器和选择。

You can implement ListSelectionListener to track selection changes in a table. Then implement TableCellRenderer that would change background of a cell with the same value of a selected object. Check out How to Use Tables for more details on JTable, renderers and selection.

这是一个非常简单的例子,展示了这个想法:

Here is a very simple example that demonstrates this idea:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

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

public class TableDemo {
    private static void createAndShowGUI() {
        JFrame frame = new JFrame("TableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel contentPanel = new JPanel();
        String[] columnNames = { "Column1", "Column2" };
        Object[][] data = { { "1", "3" }, { "2", "5" }, { "7", "1" },
                { "5", "3" } };

        JTable table = new JTable();
        MyModel model = new MyModel(Color.RED, table.getBackground());
        model.setDataVector(data, columnNames);

        table.setModel(model);
        table.setColumnSelectionAllowed(true);
        table.setDefaultRenderer(Object.class, new TestCellRenderer());

        SelectionListener listener = new SelectionListener(table);
        table.getSelectionModel().addListSelectionListener(listener);
        table.getColumnModel().getSelectionModel()
                .addListSelectionListener(listener);

        JScrollPane scrollPane = new JScrollPane(table);
        contentPanel.add(scrollPane);

        contentPanel.setOpaque(true);
        frame.add(contentPanel);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    static class TestCellRenderer extends DefaultTableCellRenderer {
        public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean hasFocus, int row,
                int column) {
            Component c = super.getTableCellRendererComponent(table, value,
                    isSelected, hasFocus, row, column);
            MyModel model = (MyModel) table.getModel();
            c.setBackground(model.getCellColor(row, column));
            return c;
        }
    }

    static class MyModel extends DefaultTableModel {
        private Object selectedObject;
        private Color selectedColor;
        private Color normalColor;

        public MyModel(Color selectedColor, Color normalColor) {
            this.selectedColor = selectedColor;
            this.normalColor = normalColor;
        }

        public Color getCellColor(int row, int column) {
            if (getValueAt(row, column).equals(selectedObject))
                return selectedColor;
            return normalColor;
        }

        public void setSelectedObject(Object selectedObject) {
            this.selectedObject = selectedObject;
            fireTableRowsUpdated(0, getRowCount());
        }
    }

    static class SelectionListener implements ListSelectionListener {
        private JTable table;

        SelectionListener(JTable table) {
            this.table = table;
        }

        public void valueChanged(ListSelectionEvent e) {
            int rowIndex = table.getSelectedRow();
            int colIndex = table.getSelectedColumn();
            if (!e.getValueIsAdjusting() && colIndex != -1 && rowIndex != -1) {
                ((MyModel) table.getModel()).setSelectedObject(table
                        .getValueAt(rowIndex, colIndex));
            }
        }
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

结果如下:

编辑:仅使用渲染器的解决方案,不使用表格模型

solution using renderer only, without table model

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

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

public class TableDemo {
    private static void createAndShowGUI() {
        JFrame frame = new JFrame("TableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel contentPanel = new JPanel();
        String[] columnNames = { "Column1", "Column2" };
        Object[][] data = { { "1", "3" }, { "2", "5" }, { "7", "1" },
                { "5", "3" } };

        JTable table = new JTable(new DefaultTableModel(data, columnNames));
        table.setColumnSelectionAllowed(true);
        TestCellRenderer renderer = new TestCellRenderer();
        table.setDefaultRenderer(Object.class, renderer);

        SelectionListener listener = new SelectionListener(table);
        table.getSelectionModel().addListSelectionListener(listener);
        table.getColumnModel().getSelectionModel()
                .addListSelectionListener(listener);

        JScrollPane scrollPane = new JScrollPane(table);
        contentPanel.add(scrollPane);

        contentPanel.setOpaque(true);
        frame.add(contentPanel);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    static class TestCellRenderer extends DefaultTableCellRenderer {

        public Component getTableCellRendererComponent(JTable table, 
                Object value, boolean isSelected, boolean hasFocus, 
                int row, int column) {

            Component c = super.getTableCellRendererComponent(table, value,
                    isSelected, hasFocus, row, column);

            int columnIndex = table.getSelectedColumn();
            int rowIndex = table.getSelectedRow();

            if (columnIndex != -1 && rowIndex != -1){
                Object selectedValue = table.getValueAt(rowIndex, columnIndex);

                if (value.equals(selectedValue)) {
                    c.setBackground(Color.RED);
                } else {
                    c.setBackground(table.getBackground());
                }
            } 
            return c;
        }
    }

    static class SelectionListener implements ListSelectionListener {
        private JTable table;

        SelectionListener(JTable table) {
            this.table = table;
        }

        public void valueChanged(ListSelectionEvent e) {
            int rowIndex = table.getSelectedRow();
            int colIndex = table.getSelectedColumn();

            if (!e.getValueIsAdjusting() && colIndex != -1 && rowIndex != -1){
                table.repaint();
            }
        }
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

这篇关于如果单元格值相同,则更改JTable中的单元格背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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