简体   繁体   English

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

[英]Set background color for particular row of JTable at runtime

I am working with netbeans IDE7.4, I am adding rows to the JTable at run-time and now I want to set background color for a particular row. 我正在使用netbeans IDE7.4,我在运行时向JTable添加行,现在我想为特定行设置背景颜色。

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的名称。

how to set background color of particular row at runtime? 如何在运行时设置特定行的背景颜色?

Use a table cell renderer. 使用表格单元格渲染器。 See How to Use Tables: Using Custom Renderers for details. 有关详细信息,请参见如何使用表:使用自定义渲染器

At some point, you need to tell the table that the content has changed in some way. 在某些时候,您需要告诉表格内容已经以某种方式发生了变化。

If you're using a TableModel based on AbstractTableModel , you can use the fireTableXxx events, for example fireTableCellUpdate(row, col) . 如果您正在使用基于AbstractTableModelTableModel ,则可以使用fireTableXxx事件,例如fireTableCellUpdate(row, col) This will inform the JTable that the model has changed and cause it repaint the table... 这将告知JTable模型已更改并导致重新绘制表格...

You may wish to consider using fireTablesRowsUpdated as this will cause the JTable to update the entire row. 您可能希望考虑使用fireTablesRowsUpdated因为这将导致JTable更新整个行。

If you are using setValueAt on the model to change the value, you will need to call the appropriate event trigger... 如果您在模型上使用setValueAt来更改值,则需要调用相应的事件触发器...

Updated with running example 更新了运行示例

So, based on you MyCellRenderer renderer, 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?? 现在的问题是,你在做什么不同?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM