2016-08-02 54 views
1

我想創建一個文件驗證器,因此,導入一個csv文件,檢查內容,檢查每個字段不是空白,然後檢查每個字段的長度。如果它大於指定的值(對於每個字段不同),則我想將其顯示爲不同的顏色,以便我可以輕鬆識別任何不適合我的數據庫的字段。如何使用數組來驗證另一個數組中的元素長度?

我設法將文件讀入數組,檢查它是否爲空,然後根據靜態值檢查字段長度。我有另一個數組包含字段大小,但我似乎無法得到交叉引用dataArrayElement 0與valaidateArrayElement 0.

我已經得到它輸出到JTable,並顯示任何命中「TOOBIG」在不同的顏色。

Integer[] validateLength = {8,2,22,11,25,13,6,2,34,11,35,35,34,11,1}; 

    class checkValue{ 
     public String validate(String value){ 
     // Check to see if the cell is null or blank 
     if (StringUtils.isNullOrBlank(value)) { 
      return "EMPTY"; 
     } else if (value.length() > 8) { //Work out how to set this as differing field lengths 
      return "TOOBIG"; 
      } 
      else { 
      return "OK"; 
      } 
     } 
    } 


class CustomRenderer extends DefaultTableCellRenderer 
{ 
private static final long serialVersionUID = 6703872492730589499L; 
private checkValue cv = new checkValue(); 

    public JComponent getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) 
    { 
     JComponent cellComponent = (JComponent) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 
     if (cv.validate(table.getValueAt(row, column).toString()).equals("TOOBIG")){ 
      cellComponent.setBackground(Color.RED); 
      cellComponent.setForeground(Color.YELLOW); 
      cellComponent.setToolTipText("Data is too big for the DB"); 
     } else if(cv.validate(table.getValueAt(row, column).toString()).equals("EMPTY")){ 
      cellComponent.setBackground(Color.GRAY); 
      cellComponent.setForeground(Color.WHITE); 
      cellComponent.setToolTipText("Field is empty in import file!"); 
     } else { 
      cellComponent.setBackground(Color.WHITE); 
      cellComponent.setForeground(Color.BLACK); 
      } 
     return cellComponent; 
    } 
} 

任何幫助,將不勝感激!

感謝

+0

*「我怎樣才能使用數組來驗證另一個數組中的元素長度?「*和.. ***你認爲這與** Swing **有關嗎? –

+0

我在JFrame上顯示它,當我創建這個問題時,它建議我添加Swing標籤,如果這增加了混淆,請致歉。 – Dan

+0

將該字段的索引(我猜它是'column')傳遞給'validate(String value)'並使用該索引來訪問'validateLength'(有一些設計問題,但我現在會忽略它們) 。 – Thomas

回答

0

您可以通過在validate方法數據元素的索引和validateLength

檢查相應的值
Integer[] validateLength = {8,2,22,11,25,13,6,2,34,11,35,35,34,11,1}; 

    public String validate(String value, int index){ 
    // Check to see if the cell is null or blank 
    if (StringUtils.isNullOrBlank(value)) { 
     return "EMPTY"; 
    } else if (value.length() > validateLength[index]) { 
     return "TOOBIG"; 
     } 
     else { 
     return "OK"; 
     } 
    } 

雖然調用此方法通過索引(假設值來驗證跨列)

validate(table.getValueAt(row, column).toString(), column); 

希望這有助於

+0

完美,謝謝,它一直讓我瘋狂! :-) (我不能標記答案,因爲我沒有足夠的聲譽,但我已經標記爲答案) – Dan

+0

很高興,幫助你..有趣的編碼:) – Sanjeev

相關問題