Java 在运行时为 JTable 的特定行设置背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22524879/
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-08-13 16:15:08  来源:igfitidea点击:

Set background color for particular row of JTable at runtime

javaswingcolorsjtable

提问by user3331894

I am working with netbeans IDE7.4, I am adding rows to the JTableat run-time and now I want to set background color for a particular row.

我正在使用 netbeans IDE7.4,我JTable在运行时向 IDE 添加行,现在我想为特定行设置背景颜色。

Now the problem is that when the value of that row is changed the color of that particular row is not changed and when I scroll up or down the table the changes are applied.

现在的问题是,当该行的值更改时,该特定行的颜色不会更改,并且当我向上或向下滚动表格时,会应用更改。

How to refresh the table at run-time? How to set background color of particular row at runtime?

如何在运行时刷新表?如何在运行时设置特定行的背景颜色?

This is renderer class am using for coloring particular row:

这是用于着色特定行的渲染器类:

public class MyCellRenderer extends javax.swing.table.DefaultTableCellRenderer
    {         
public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table, java.lang.Object value, boolean isSelected,     boolean hasFocus, int row, int column)
   {
   final java.awt.Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,        column);

     Object val=table.getValueAt(row, 2);
     String sval=val.toString();
     sval=sval.replaceAll(":","");
     int ival=Integer.parseInt(sval);
  if(ival==0) 
    {  
        cellComponent.setForeground(Color.black);          
        cellComponent.setBackground(Color.red);              

    }      
    else  
    {      
        cellComponent.setBackground(Color.white);      
        cellComponent.setForeground(Color.black);      
    }    
    if (isSelected)
   {
    cellComponent.setForeground(table.getSelectionForeground());                             cellComponent.setBackground(table.getSelectionBackground());
   }


      return cellComponent;

 }


 }

and am assigning to jtable like this :

并像这样分配给 jtable :

    newViewTable.setDefaultRenderer(Object.class,new MyCellRenderer());

newViewTable is the name of JTable.

newViewTable 是 JTable 的名称。

采纳答案by MadProgrammer

At some point, you need to tell the table that the content has changed in some way.

在某些时候,您需要告诉表格内容以某种方式发生了变化。

If you're using a TableModelbased on AbstractTableModel, you can use the fireTableXxxevents, for example fireTableCellUpdate(row, col). This will inform the JTablethat the model has changed and cause it repaint the table...

如果您使用的是TableModel基于AbstractTableModel,则可以使用fireTableXxx事件,例如fireTableCellUpdate(row, col)。这将通知JTable模型已更改并导致它重新绘制表格...

You may wish to consider using fireTablesRowsUpdatedas this will cause the JTableto update the entire row.

您可能希望考虑使用,fireTablesRowsUpdated因为这将导致JTable更新整行。

If you are using setValueAton the model to change the value, you will need to call the appropriate event trigger...

如果您setValueAt在模型上使用来更改值,则需要调用适当的事件触发器...

Updated with running example

更新了运行示例

So, based on you MyCellRendererrenderer, I did this example, and it works fine...

所以,基于你的MyCellRenderer渲染器,我做了这个例子,它工作正常......

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class TestTable {

    public static void main(String[] args) {
        new TestTable();
    }

    public TestTable() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                final DefaultTableModel model = new DefaultTableModel(
                        new Object[]{"A", "B", "C"}, 
                        0
                );

                model.addRow(new Object[]{"A", "B", "1"});
                model.addRow(new Object[]{"C", "D", "0"});
                model.addRow(new Object[]{"E", "F", "1"});
                model.addRow(new Object[]{"G", "H", "0"});

                JTable table = new JTable(model);
                table.setDefaultRenderer(Object.class, new MyCellRenderer());

                JButton btn = new JButton("Add");
                btn.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        model.addRow(new Object[]{"N", "O", (int)(Math.round(Math.random() * 1))});
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(table));
                frame.add(btn, BorderLayout.SOUTH);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MyCellRenderer extends javax.swing.table.DefaultTableCellRenderer {

        public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table, java.lang.Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            final java.awt.Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

            Object val = table.getValueAt(row, 2);
            String sval = val.toString();
            sval = sval.replaceAll(":", "");
            int ival = Integer.parseInt(sval);
            if (ival == 0) {
                cellComponent.setForeground(Color.black);
                cellComponent.setBackground(Color.red);

            } else {
                cellComponent.setBackground(Color.white);
                cellComponent.setForeground(Color.black);
            }
            if (isSelected) {
                cellComponent.setForeground(table.getSelectionForeground());
                cellComponent.setBackground(table.getSelectionBackground());
            }

            return cellComponent;

        }

    }

}

The question now is, what are you doing differently??

现在的问题是,你在做什么不同?

回答by Andrew Thompson

how to set background color of particular row at runtime?

如何在运行时设置特定行的背景颜色?

Use a table cell renderer. See How to Use Tables: Using Custom Renderersfor details.

使用表格单元格渲染器。有关详细信息,请参阅如何使用表:使用自定义呈现器