java JTable 单元格颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12861402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:32:19  来源:igfitidea点击:

JTable Cell Color

javaswingcolorsjtabletablecellrenderer

提问by user1154644

Can someone give me an example of how to get the background color of a particular cell in a JTable? I am unable to find an example of how to do this. Plenty of examples on getting the value in a cell, but not the background color of a cell.

有人可以举个例子来说明如何获取 JTable 中特定单元格的背景颜色吗?我无法找到如何执行此操作的示例。有很多关于获取单元格中的值的例子,但不是单元格的背景颜色。

回答by Renat Gilmanov

It should be something like the following (fixed according to all comments):

它应该类似于以下内容(根据所有评论修复):

Important: use table.prepareRenderer(...) to let JTable do all work for you

重要提示:使用 table.prepareRenderer(...) 让 JTable 为您完成所有工作

public Color getTableCellBackground(JTable table, int row, int col) {
    TableCellRenderer renderer = table.getCellRenderer(row, col);
    Component component = table.prepareRenderer(renderer, row, col);
    return component.getBackground();
}

Full demo:

完整演示:

public class TableRenderDemo extends JPanel {

    public TableRenderDemo() {
        super(new GridLayout(1, 0));

        final JTable table = new JTable(new MyTableModel());
        table.setPreferredScrollableViewportSize(new Dimension(600, 200));
        table.setFillsViewportHeight(true);
        table.setDefaultRenderer(Object.class, new MyRenderer());

        table.addMouseListener(new MouseAdapter() {

            public void mouseClicked(MouseEvent e) {
                int row = table.getSelectedRow();
                int col = table.getSelectedColumn();

                JOptionPane.showInternalMessageDialog(TableRenderDemo.this,
                        "Color: " + getTableCellBackground(table, row, col));

                System.out.println("Color: " + getTableCellBackground(table, row, col));
            }
        });

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }

    public Color getTableCellBackground(JTable table, int row, int col) {
        TableCellRenderer renderer = table.getCellRenderer(row, col);
        Component component = table.prepareRenderer(renderer, row, col);    
        return component.getBackground();
    }

    class MyRenderer implements TableCellRenderer {

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JTextField editor = new JTextField();
            if (value != null) {
                editor.setText(value.toString());
            }
            editor.setBackground((row % 2 == 0) ? Color.white : Color.BLUE);
            return editor;
        }
    }

    class MyTableModel extends AbstractTableModel {

        private String[] columnNames = {"First Name",
            "Last Name",
            "Sport",
            "# of Years",
            "Vegetarian"};
        private Object[][] data = {
            {"Kathy", "Smith",
                "Snowboarding", new Integer(5), new Boolean(false)},
            {"John", "Doe",
                "Rowing", new Integer(3), new Boolean(true)},
            {"Sue", "Black",
                "Knitting", new Integer(2), new Boolean(false)},
            {"Jane", "White",
                "Speed reading", new Integer(20), new Boolean(true)},
            {"Joe", "Brown",
                "Pool", new Integer(10), new Boolean(false)}
        };
        public final Object[] longValues = {"Jane", "Kathy",
            "None of the above",
            new Integer(20), Boolean.TRUE};

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }
    }

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

        TableRenderDemo newContentPane = new TableRenderDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

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

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

            public void run() {
                createAndShowGUI();
            }
        });
    }
}

回答by mKorbel

Can someone give me an example of how to get the background color of a particular cell in a JTable? I am unable to find an example of how to do this.

有人可以举个例子来说明如何获取 JTable 中特定单元格的背景颜色吗?我无法找到如何执行此操作的示例。

Plenty of examples on getting the value in a cell, but not the background color of a cell.

有很多关于获取单元格中的值的例子,但不是单元格的背景颜色。

  • I can't resist, please on this forum or where

  • I hope that help you ....

  • 我无法抗拒,请在这个论坛或哪里

  • 希望能帮到你......

回答by Reimeus

To get the JTablecolor at cell 0, 0you could get the background color of the cell component:

要获取JTable单元格的颜色,0, 0您可以获取单元格组件的背景颜色:

TableCellRenderer cellRenderer = table.getCellRenderer(0, 0);
Component rendererComponent = cellRenderer.getTableCellRendererComponent(table, null, false, true, 0, 0);
Color cellColor = rendererComponent.getBackground();

回答by Raghunandan

Use TableCellRenderer

使用 TableCellRenderer

jTable1 = new javax.swing.JTable(6,6){
public Component prepareRenderer(
    TableCellRenderer renderer, int row, int column)
{

    Component c = super.prepareRenderer(renderer, row, column);
    if(column==2 && row==4)
    {
       Color color= c.getBackground();// use setBackground to set color and get background to get background of a particular cell
       System.out.println("Color of row=0 and column=0 is "+color);

    }

    else
    {
        c.setBackground(Color.GREEN);
        setShowGrid(true);
    }
    return c;

}
};