简体   繁体   中英

How to color specific rows in a JTable

I want the ability to highlight some rows of JTable , depending on the values in the row itself. For example, if the existing qty < reorder level , that row should be highlighted in the JTable .

I know there is a table method tblItems.setSelectionBackground(Color.yellow); that works when the rows are selected, but is there a similar method that doesn't rely on the rows being selected to have them show in a different color?

public class MyTableCellRenderer implements TableCellRenderer {  
    @Override  
    public Component getTableCellRendererComponent
(JTable table, Object value, 
boolean isSelected, boolean hasFocus, int row, int column) {

        Object ob=table.getValueAt(row, column);
        if(ob.toString().equals("yes")){
            //need to colour the entire row
        }
        return 
    }

}

you could use my answer to change the color of the cell. the same technique could be used to apply it to each cell in the row.

This is also example with prepareRenderer

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;

public class TableWithPrepareRendererExample extends JFrame {
  ColorName colors[] = { new ColorName("Red"), new ColorName("Green"), new ColorName("Blue"),
    new ColorName("Black"), new ColorName("White") };

  public TableWithPrepareRendererExample() {
    super("Table With prepareRenderer Example");
    setSize(500, 300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    JTable table = new JTable(new AbstractTableModel() {
      ColorName data[] = { colors[0], colors[1], colors[2], colors[3], colors[4], colors[0],
        colors[1], colors[2], colors[3], colors[4] };


      public int getColumnCount() {
        return 3;
      }

      public int getRowCount() {
        return 10;
      }

      public Object getValueAt(int r, int c) {
        switch (c) {
          case 0:
            return (r + 1) + ".";
          case 1:
            return "Some pithy quote #" + r;
          case 2:
            return data[r];
        }
        return "Bad Column";
      }

      public Class getColumnClass(int c) {
        if (c == 2)
          return ColorName.class;
        return String.class;
      }

      public boolean isCellEditable(int r, int c) {
        return c == 2;
      }

      public void setValueAt(Object value, int r, int c) {
        data[r] = (ColorName) value;
      }

    }) {
      public Component prepareRenderer(TableCellRenderer renderer,
                                       int rowIndex, int vColIndex) {
        Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
        Object value = getValueAt(rowIndex, vColIndex);
        if (value.toString().equals("Red"))
          c.setBackground(Color.RED);
        else {
          if (rowIndex % 2 == 0 && !isCellSelected(rowIndex, vColIndex)) {
            c.setBackground(Color.YELLOW);
          } else {
            // If not shaded, match the table's background
            c.setBackground(getBackground());
          }
        }
        return c;
      }
    };

    JComboBox combo = new JComboBox(colors);
    table.setDefaultEditor(ColorName.class, new DefaultCellEditor(combo));
    table.setRowHeight(20);
    getContentPane().add(new JScrollPane(table));
  }

  public static void main(String args[]) {
    TableWithPrepareRendererExample ex = new TableWithPrepareRendererExample();
    ex.setVisible(true);
  }

  public class ColorName {
    String cname;

    public ColorName(String name) {
      cname = name;
    }

    public String toString() {
      return cname;
    }
  }

}

The way I'd do it, is to modify the code that JTable uses to paint the table cells...

Implement your own TableCellRenderer . In the getTableCellRendererComponent() method, check to see whether the qty < reorder level, as you wanted, and if it is, call setBackgroundColor() on the Component before you return it from this method. The easiest way to write a TableCellRenderer is to look at the source code for the existing TableCellRenderer used by JTable - it only has 1 method and you can basically just copy it and add in a little bit of code to do your color-checking. You set the TableCellRenderer on the JTable using setDefaultRenderer()

As mentioned by @mKorbel in the comments, you could also achieve a similar thing by overwriting the JTable prepareRenderer() method.

Its not that hard to do, especially if you look at the existing Java source code to see how they do it.

在此处输入图片说明

private JTable table;
private SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");

public TablePrepareRenderer() {
    Object[] columnNames = { "Type", "Company", "Name", "Salery", "Designation" };
    Object[][] data =
    { { "Probation", "Digital Research Lab", "Kamran Ali", "500,000", "Java Developer" }, { "Permenent", "Netsole",
                                                                                            "Farhan Khan",
                                                                                            "80,000",
                                                                                            "System Administaror" },
      { "Contract", "System Limited", "Danyal", "100,000", "Network Administrator" },
      { "Probation", "TeraData", "Ali Raza", "45,000", "IT Officer" },
      { "Contract", "MicroSoft", "Sikandar Hayat", "450,000", "Team Lead" },
      { "Permenent", "MicroSoft", "Adnan", "30,000", "Driver" }, };
    DefaultTableModel model = new DefaultTableModel(data, columnNames) {

        private static final long serialVersionUID = 1L;

        @Override
        public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }
    };
    table = new JTable(model) {

            private static final long serialVersionUID = 1L;

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

                if (!isRowSelected(row)) {
                    if (table.getColumnCount() >= 0) {
                        String type = (String)getModel().getValueAt(row, 0);
                        if (type.equalsIgnoreCase("Probation")) {
                            c.setBackground(new Color(198, 190, 255));

                        }
                        if (type.equalsIgnoreCase("Permenent")) {
                            c.setBackground(new Color(14, 255, 190));

                        }
                        if (type.equalsIgnoreCase("Contract")) {
                            c.setBackground(Color.green);

                        }

                    }
                }
                if (isRowSelected(row) && isColumnSelected(column)) {
                    ((JComponent)c).setBorder(new LineBorder(Color.red));
                }
                return c;
            }
        };

    table.setPreferredScrollableViewportSize(table.getPreferredSize());
    JScrollPane scrollPane = new JScrollPane(table);
    getContentPane().add(scrollPane);
}


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

        @Override
        public void run() {
            TablePrepareRenderer frame = new TablePrepareRenderer();
            frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocation(150, 150);
            frame.setSize(800, 500);
            frame.setVisible(true);


        }
    });
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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