2012-08-24 170 views
2

我CustomTableCellRender如何更改背景顏色在一定的表格單元格


public class CustomCellRenderer extends JLabel implements TableCellRenderer { 

    private TableCellRenderer defaultCellRenderer; 

    public CustomCellRenderer(TableCellRenderer defaultCellRenderer) { 
     this.defaultCellRenderer = defaultCellRenderer; 
    } 

    public Component getTableCellRendererComponent(JTable table, Object ovalue, boolean isSelected, boolean hasFocus, int row, int column) { 
     String val = (String) ovalue; 
     Component c = defaultCellRenderer.getTableCellRendererComponent(table, ovalue, isSelected, hasFocus, row, column); 
     if (c != null) { 
      if (val.equals("0h")) { 
       c.setForeground(Color.RED); 
      } else { 
       c.setForeground(table.getForeground()); 
      } 
      return c; 
     } else return null; 
    } 
} 

...



      TableCellRenderer renderer = new CustomCellRenderer(sumTable.getDefaultRenderer(columnModel.getColumn(i).getClass())); 
      columnModel.getColumn(i).setCellRenderer(renderer); 

,它的工作正常UTIL我需要更改單元格背景顏色它設置顏色不能在某些細胞並在所有列中顯示所有單元格。


... 
      if (val.equals("0h")) { 
       c.setBackground(Color.GRAY); 
      } else { 
       c.setForeground(table.getForeground()); 
      } 
... 

我需要做什麼?

回答

2

在您的其他語句中,您需要將背景設置回某些內容。例如。 :
c.setBackground(Color.WHITE);

+0

你說得對。只是我沒有注意 – guzick

2

什麼我需要做什麼?

public Component getTableCellRendererComponent(
    JTable table, Object ovalue, boolean isSelected, 
    boolean hasFocus, int row, int column) { 
  • 有兩個參數int rowint column使用在JTable矩陣這兩個座標,

  • 必須接受和不僞造者,所有(???)Arrays in Java開始使用zero

  • (0, 0)first columnfirst row

編輯

one of ways

import java.awt.*; 
import java.util.Vector; 
import java.util.regex.Pattern; 
import javax.swing.*; 
import javax.swing.table.*; 

public class HiglightNumberValueInTableCell { 

    private String testS; 
    private JFrame frame = new JFrame("frameTitle"); 
    private JScrollPane tblS = new JScrollPane(); 
    private JTable tbl; 
    private Vector<String> rOrH; 
    private long t1 = 0L; 
    private long t2 = 0L; 

    public HiglightNumberValueInTableCell() { 
     t1 = System.currentTimeMillis(); 
     int regLenght = 25000; 
     int chars = 0; 
     AlphaChars aChars = new AlphaChars(); 
     testS = aChars.getNext(regLenght); 
     rOrH = new Vector<String>(); 
     Vector<Vector<String>> rowD = new Vector<Vector<String>>(); 
     for (int e = 0; e < regLenght;) { 
      chars++; 
      //if (chars > 50) { //one char in table cell 
      if (chars > 20) { 
       chars = 1; 
       rowD.add(rOrH); 
       rOrH = new Vector<String>(); 
      } 
      //String str = (testS.substring(e, (e + 1))).toString();//one char in table cell 
      String str = (testS.substring(e, (e + 5))).toString(); 
      if (str != null) { 
       rOrH.add(str); 
      } else { 
       rOrH.add(""); 
      } 
      //e++;//one char in table cell 
      e += 5; 
     } 
     rOrH = new Vector<String>(); 
     //for (int i = 0; i < 50; i++) {//one char in table cell 
     for (int i = 0; i < 20; i++) { 
      rOrH.add(String.valueOf(i + 1)); 
     } 
     tbl = new JTable(rowD, rOrH); 
     tblS = new JScrollPane(tbl, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, 
       ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); 
     tblS.setPreferredSize(new Dimension(1000, 403)); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.add(tblS, BorderLayout.CENTER); 
     frame.setLocation(50, 50); 
     frame.pack(); 
     addColumnRenderes(); 
    } 

    private void addColumnRenderes() { 
     for (int i = 0; i < tbl.getColumnCount(); i++) { 
      RowColorRenderer rowRenderer = new RowColorRenderer(i); 
      TableColumn column = tbl.getColumnModel().getColumn(i); 
      column.setCellRenderer(rowRenderer); 
     } 
     Runnable doRun = new Runnable() { 

      @Override 
      public void run() { 
       showFrame(); 
      } 
     }; 
     SwingUtilities.invokeLater(doRun); 
    } 

    private void showFrame() { 
     Runnable doRun = new Runnable() { 

      @Override 
      public void run() { 
       frame.setVisible(true); 
       t2 = System.currentTimeMillis(); 
       System.out.println("miliSec:" + (t2 - t1)); //aver. 45 miliSec. 
      } 
     }; 
     SwingUtilities.invokeLater(doRun); 
    } 

    private class RowColorRenderer extends DefaultTableCellRenderer { 

     private static final long serialVersionUID = 1L; 
     private int colNo = 0; 

     RowColorRenderer(int col) { 
      colNo = col; 
     } 

     @Override 
     public Component getTableCellRendererComponent(JTable table, Object value, 
       boolean isSelected, boolean hasFocus, int row, int column) { 
      Component comp = super.getTableCellRendererComponent(table, value, 
        isSelected, hasFocus, row, column); 
      JComponent jc = (JComponent) comp; 
      if (!isSelected) { 
       if (table.getValueAt(row, colNo) != null) { 
        String str = table.getValueAt(row, colNo).toString(); 
        if (!str.isEmpty()) { 
         if (Pattern.compile("\\d").matcher(str).find()) { 
          if (((Pattern.compile("[02468]").matcher(str).find())) 
            && (!(Pattern.compile("[13579]").matcher(str).find()))) { 
           setForeground(Color.magenta); 
           setBackground(Color.orange); 
          } else if ((!(Pattern.compile("[02468]").matcher(str).find())) 
            && ((Pattern.compile("[13579]").matcher(str).find()))) { 
           setForeground(Color.blue); 
           setBackground(Color.yellow); 
          } else if (((Pattern.compile("[02468]").matcher(str).find())) 
            && ((Pattern.compile("[13579]").matcher(str).find()))) { 
           setForeground(Color.red); 
           setBackground(Color.cyan); 
          } 
          setFont(new Font("Serif", Font.BOLD, 12)); 
          setHorizontalAlignment(CENTER); 
         } else { 
          setBackground(table.getBackground()); 
          setForeground(table.getForeground()); 
          setFont(new Font("Serif", Font.PLAIN, 8)); 
          setHorizontalAlignment(CENTER); 
         } 
        } 
       } 
      } 
      return this; 
     } 
    } 

    private class AlphaChars { 

     public static final int MIN_LENGTH = 2000; 
     private java.util.Random rand = new java.util.Random(); 
     private char[] AlphaChars = { 
      'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 
      'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 
      'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 
      'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 
      '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '+', '-', '*', '/', '<', '>', '&', 
      '#', '@', '{', '}', '?', ':', '_', '"', '!', ')', '('}; 

     public String getNext() { 
      StringBuilder strbuf = new StringBuilder(); 
      for (int i = 0; i < MIN_LENGTH; i++) { 
       strbuf.append(getAlphaChars()[getRand().nextInt(getAlphaChars().length)]); 
      } 
      return strbuf.toString(); 
     } 

     public String getNext(int reqLenght) { 
      StringBuilder strbuf = new StringBuilder(); 
      for (int i = 0; i < reqLenght; i++) { 
       strbuf.append(getAlphaChars()[getRand().nextInt(getAlphaChars().length)]); 
      } 
      return strbuf.toString(); 
     } 

     public java.util.Random getRand() { 
      return rand; 
     } 

     public void setRand(java.util.Random aRand) { 
      rand = aRand; 
     } 

     public char[] getAlphaChars() { 
      return AlphaChars; 
     } 

     public void setAlphaChars(char[] aAlphaChars) { 
      AlphaChars = aAlphaChars; 
     } 
    } 

    public static void main(String args[]) { 
     HiglightNumberValueInTableCell hnvit = new HiglightNumberValueInTableCell(); 
    } 
} 
+2

也考慮['prepareRenderer()'](http://stackoverflow.com/a/5799016/230513) – trashgod

+0

我需要更改單元格中的背景顏色,其中被寫爲「0h」,但我得到所有單元格與背景顏色灰色。 我記得,在java中的數組從零開始,但這對我有什麼幫助? – guzick

+0

沒什麼複雜的,看我在這裏編輯 – mKorbel

3

的原因是(經常)的DefaultTableCellRenderer臭名昭著的色彩記憶,described in a recent answer

在特定情況下的問題是,您使用與委託相同的渲染器實例作爲默認渲染器在別處。最簡單的解決方案是使用2個不同的實例(畢竟,您知道默認安裝哪種類型的渲染器)。

自定義着色(或其他單元格的視覺裝飾)最簡單的解決方案是使用SwingX以及對呈現組件的一致配置支持。

+0

+1一個重要的警告。 – trashgod

相關問題