jTable将所有内容排序为String

时间:2018-11-24 16:27:15

标签: java mysql swing jtable columnsorting

我从MySQL(JDBC)数据库下载数据并将其显示在PreparedStatement pstmt = (PreparedStatement) connection.prepareStatement(query); pstmt.setInt(1,idUser); result = pstmt.executeQuery(); jTable.setModel(DbUtils.resultSetToTableModel(result)); 中:

jTable

我使用Netbeans,在autoCreateRowSorter选项设置为true的属性中的jTable.setModel(DbUtils.resultSetToTableModel(result)); 上。排序有效,但是,某些列应按int值进行排序,例如用户ID排序为字符串。我不知道如何以允许我选择列类型的方式初始化表。然后排序应该可以正常工作。也许可以在下面的代码行中完成此操作,这就是为什么我要向经验丰富的人寻求建议。

UserID(int) / name(String) / surname(String) / phone number(int) / 
dateTime(e.g. 2018-11-03 19:02:45 - may remain in the programme as String)

我还可以添加表中的列的样子:

  <?php
    if (isset($_GET['username'])){//only echo user name if requested from js do not include header or footer 
        $username = $_GET['username'];     
        if (!empty($username)){
            echo 'You have selected user: '.$username ;
        }
    }else{//you can include here your headers
        ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
    <tr>
        <td>
            <select name="user" id="user" >
                  <option disabled selected value> - Select User - </option>
                  <?php 
                    $sql_select = mysqli_query($conn,"SELECT username, surname, fname FROM user WHERE v_flag != 0 ORDER BY surname ASC ");
                        while ($result = mysqli_fetch_assoc($sql_select)){
                            $name = ($result['surname']. ', '.$result['fname']);
                            echo '<option value = " '.$result['username']. '">'.$name.'</option>';
                        }
                    ?>                          
            </select>
        </td>  </tr> <tr><td> <span id="username">
         <?php if (isset($_POST['username'])){//show if submitted from html form
        $username = $_POST['username'];     
        if (!empty($username)){
            echo 'You have selected user: '.$username ;
        }
    }
    ?>  </span></td>                   
    </tr>
</table>        
<script type="text/javascript">
$(document).ready(function() {
  $("#user").change(function() {        
  var user = $(this).val();
      $.ajax({
        url:"test2.php?username="+user,
        success:function(response) {
            $("#username").html(response);
        }
      });
  });
}); 
</script>
 <?php
    //you can include here your footers

    }
?>

1 个答案:

答案 0 :(得分:0)

您需要覆盖getColumnClass(...)中的JTable来告诉表格每一列中的数据类型,以便表格可以使用适当的渲染/编辑器,而Compartor列。

类似的东西:

@Override
public Class getColumnClass(int column)
{
    for (int row = 0; row < getRowCount(); row++)
    {
        Object o = getValueAt(row, column);

        if (o != null)
        {
            return o.getClass();
        }
    }

    return Object.class;
}