验证jtable是否为空?

时间:2015-03-14 20:53:16

标签: java validation jtable

我需要知道如何检查JTable中是否有数据

if(jTextField1.getText().isEmpty()):
    then (if jTable1.isEmpty())
        ...

我是怎么做到的?

2 个答案:

答案 0 :(得分:1)

JTables不像jtextfield这样的简单组件,就像其他具有底层数据模型的swing组件一样,请从javadoc中查看此示例:

  TableModel dataModel = new AbstractTableModel() {
      public int getColumnCount() { return 10; }
      public int getRowCount() { return 10;}
      public Object getValueAt(int row, int col) { return new Integer(row*col); }
  };
  JTable table = new JTable(dataModel);

与遵循MVC模式的每个UI对象一样,您不使用图形组件来理解它具有的值,而是使用数据模型。在这种情况下,保存对您创建的JTable的数据模型的引用,并调用getRowCount以了解您之前加载了多少数据。

另外,请查看官方文档here

答案 1 :(得分:1)

我验证jtable是否为空     这段代码。

private int calculate() {
    Vector<Integer> myvector = new Vector();

    TableModel mode = new DefaultTableModel();
    mode = jTable2.getModel();
    int n = mode.getRowCount();
    for (int i = 0; i < n; i++) {
        if (mode.getValueAt(i, 3) != null) {

            myvector.add((Integer) mode.getValueAt(i, 3));
        }
    }
    return myvector.size();
}

//then I validate with a button
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    int numofvalidrows;
    numofvalidrows = calculate();

    if (numofvalidrows == 0) //if the size of the vector is 0 then the jtable is empty
    {
        System.out.println("You need to add people to the jtable, because the table is empty");
    } else {
        // I get the values of the jtable with 
        for (int i = 0; i < n; i++) {
            if (model.getValueAt(i, 3) != null) {  //whith this "if" I print only data, not print null of the empty cells in jtable
                System.out.print(model.getValueAt(i, 3)) 

            }

        }
    }
}
相关问题