将表列定义为仅包含十六进制数

时间:2016-05-22 06:59:34

标签: java swing jtable hex tablecellrenderer

我有一个列数量的JTable。 我有兴趣让其中一列只接受十六进制数字。 数字的格式为: 0X [0-9A-FA-F] *

我该如何创建它? 如果我可以添加“错误”指示将是伟大的

1 个答案:

答案 0 :(得分:0)

试试这个:

boolean isValidHex(String s) {
        return s.matches("0x[0-9a-fA-F]*");
}

void addNumberToColumn(int number) {
    String s = "0x" + Integer.toHexString(number);
    if (isValidHex(s)) {
        // accept/add to column
    } else {
        // produce error/show error message
    }
}

如果你能提供你的代码,那就太好了,这样你的问题就会更清晰。

修改 好的,如果我理解正确,你可以使用

  

TableDemo.java

并且您只想验证用户输入,以便他可以输入HEX格式的数字或不输入(或者更确切地说它应该显示错误)。
十六进制整数可以表示为字符串,所以首先,你必须更改data数组,告诉你TableModel你将在“#中使用字符串(但不是整数)”#年“ - 列:

private Object[][] data = {
            {"Kathy", "Smith",
                "Snowboarding", "5", new Boolean(false)}, // or new String("5") if you want :)
            {"John", "Doe",
                "Rowing", "3", new Boolean(true)},
            {"Sue", "Black",
                "Knitting", "2", new Boolean(false)},
            {"Jane", "White",
                "Speed reading", "2", new Boolean(true)},
            {"Joe", "Brown",
                "Pool", "10", new Boolean(false)}
};

下一步是修改setValueAt()方法:

public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
        System.out.println("Setting value at " + row + "," + col
                + " to " + value
                + " (an instance of "
                + value.getClass() + ")");
    }

    if (col == 3) { // num of Years column
        boolean isValidHex = ((String) value).matches("0x[0-9a-fA-F]*");
        if (isValidHex) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
        } else {
            data[row][col] = "Error: Wrong format!";
        }
    } else {
        data[row][col] = value;
        fireTableCellUpdated(row, col);
    }

    if (DEBUG) {
        System.out.println("New value of data:");
        printDebugData();
    }
}