我想創建一個文件驗證器,因此,導入一個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;
}
}
任何幫助,將不勝感激!
感謝
*「我怎樣才能使用數組來驗證另一個數組中的元素長度?「*和.. ***你認爲這與** Swing **有關嗎? –
我在JFrame上顯示它,當我創建這個問題時,它建議我添加Swing標籤,如果這增加了混淆,請致歉。 – Dan
將該字段的索引(我猜它是'column')傳遞給'validate(String value)'並使用該索引來訪問'validateLength'(有一些設計問題,但我現在會忽略它們) 。 – Thomas