如何为JTable中的特定行着色

时间:2012-10-27 09:25:28

标签: java swing jtable renderer tablecellrenderer

我希望能够突出显示JTable的某些行,具体取决于行本身的值。例如,如果现有数量< 重新订购级别,该行应在JTable

中突出显示

我知道有一个表方法tblItems.setSelectionBackground(Color.yellow);在选择行时有效,但是有一个类似的方法不依赖于被选中的行让它们以不同的颜色显示吗?

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 
    }

}

3 个答案:

答案 0 :(得分:2)

您可以使用my answer更改单元格的颜色。可以使用相同的技术将其应用于行中的每个单元格。

这也是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;
    }
  }

}

答案 1 :(得分:1)

我这样做的方法是修改JTable用于绘制表格单元格的代码......

实施您自己的TableCellRenderer。在getTableCellRendererComponent()方法中,检查qty<根据需要重新排序级别,如果是,请在从此方法返回之前在setBackgroundColor()上调用Component。编写TableCellRenderer的最简单方法是查看TableCellRenderer使用的现有JTable的源代码 - 它只有1个方法,您基本上只需复制它并添加一个一点点代码来进行颜色检查。您使用TableCellRenderer

JTable上设置setDefaultRenderer()

正如@mKorbel在评论中所提到的,你也可以通过覆盖JTable prepareRenderer()方法来实现类似的事情。

它并不难做到,特别是如果你查看现有的Java源代码,看看它们是如何做到的。

答案 2 :(得分:0)

enter image description here

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);


        }
    });
}

}