简体   繁体   中英

How can I get all the different rows that have one shared piece of info in a jTable?

I'm new here and new to programming in general, so I'm sorry if I don't call things by their actual names.

So I'm working with a jTable and I'm trying to get the table to show me all of the people that live in the same place (in my database I have 2 people that live in the place "champa"), instead of just showing me the first person that has said place in their "location" atribute. This is the code I'm using that only shows me the first person that meets the requirements, instead of showing me all of the people that do meet them:

private void cargarLocalidad() {
    dtm.setRowCount(0);
    HabitanteADO h_ado = new HabitanteADO();
    Habitante habi = null;
    String [] habitantes = new String[7];
    String localidad = txtBuscar.getText().trim().toLowerCase();
    if(localidad.length() == 0) {
        ArrayList<Habitante> arregloHabitante = h_ado.readByAll();
        for(Habitante h : arregloHabitante) {
            habitantes[0] = h.getRut();
            habitantes[1] = h.getNombre();
            habitantes[2] = h.getGenero();
            habitantes[3] = h.getFecha().toString();
            habitantes[4] = h.getDireccion();
            habitantes[5] = h.getLocalidad().toLowerCase();
            habitantes[6] = String.valueOf(h.getVulnerabilidad());
            dtm.addRow(habitantes);
            txtBuscar.setText("");
            txtBuscar.requestFocus();
 }

    } else {
        habi = h_ado.readByLocalidad(localidad);
        if(habi != null) {
            habitantes[0] = habi.getRut();
            habitantes[1] = habi.getNombre();
            habitantes[2] = habi.getGenero();
            habitantes[3] = habi.getFecha().toString();
            habitantes[4] = habi.getDireccion();
            habitantes[5] = habi.getLocalidad();
            habitantes[6] = String.valueOf(habi.getVulnerabilidad());
            dtm.addRow(habitantes);
            txtBuscar.setText("");
            txtBuscar.requestFocus();
        } else
            mensaje("La localidad que busca no existe!");
            txtBuscar.setText("");
            txtBuscar.requestFocus();
}
    }

The portion of the code that comes after the else is the one that only shows me the first person that has the location that I enter in the text field. I need it to show me all of the people that share said location, so if I type in "champa" I want the jTable to load up all of the people in my database that live there, not only the first person that does. Thanks in advance, this is my first post here so I'm sorry for any mistakes!

You should be able to display this information within your JTable by properly querying your database for that information, for example:

String sql = "SELECT * FROM MyTableName WHERE city='champa';"

You can also use JTable's TableRowSorter class along with RowFilter.regexFilter() method to filter the entire contents of the JTable to display only the desired records, for example here is a method to do this for you (read the JavaDoc):

/**
 * Make sure the supplied JTable's DefaultTableModel already contains data
 * before calling this method.<br><br>
 * <p>
 * The JTable always retains the data it is currently filled with within its
 * Table Model. <b>Knowing this we can theoretically fill the Table with all
 * database table records then use the Filter to display only the specific
 * table records we want.</b> This way we don't have to pole the database
 * for different records all the time and records acquisition is greatly
 * increased.<br><br>
 * <p>
 * This method will pass the supplied Filter text across the supplied JTable
 * and will force that JTable to only display records (contained within that
 * JTable at the time) which contains that specific text. It reacts very
 * much like a search engine for the JTable.<br><br>
 * <p>
 * If you want to display all records again which were originally contained
 * within the supplied JTable then just pass a Null String ("") within the
 * filterText parameter of this method.<br><br>
 *
 * @param table          (JTable) The JTable to run filter on.<br>
 *
 * @param searchCriteria (String) The text to filter JTable with. Passing a 
 * Null String ("") will force the table to display all records. Regular 
 * Expressions (RegEx) can also be supplied within the criteria string. If 
 * the wildcard characters <b>?</b> or <b>*</b> are supplied within the filter 
 * criteria String without any RegEx meta characters then the functional purpose 
 * of these two wildcard characters are converted to RegEx when encountered. If 
 * actual Regular Expressions are going to be used to make up the search criteria 
 * string then be sure to set the <b>endorseWildcards</b> optional parameter to 
 * boolean false since the <b>?</b> and <b>*</b> wildcard characters have 
 * different meaning within a Regular Expression and must be handled differently.<br>
 *
 * @param options (optional - Integer/Boolean):<pre>
 * 
 *     byColumnNumber - (Optional - Integer - Default is -1) By default
 *                       this method filters across all table columns but
 *                       you can be column specific if you pass a column
 *                       number to this optional parameter. This parameter
 *                       accepts only a <b>Literal Column Number</b> which
 *                       means that although the first column within a
 *                       JTable is considered column 0, to this method it is
 *                       considered as column 1.
 * 
 *    endorseWildcards - (boolean) Default is true (allow wildcards). If true 
 *                       then when a wildcard character is encountered within
 *                       a search criteria string it is automatically converted
 *                       to its RegEx equivalent. The two wildcard characters 
 *                       are almost always more than enough to carry out any 
 *                       search required and is usually much easier to use than 
 *                       some complex regular expressions. If endorseWildcards
 *                       is true then upper or lower letter case is ignored as
 *                       well.
 * 
 *                       If you provide a true of false to this parameter then
 *                       you must provide a value (or null) to the option 
 *                       <b>byColumnNumber</b> parameter.</pre>
 */
public static void filterTable(JTable table, String searchCriteria, Object... options) {
    int column = -1;
    boolean endorseWildcards = true;
    if (options.length > 0) {
        if (options[0] != null) {
            column = (int)options[0] - 1;
        }
        if (options.length >= 2) {
            if (options[1] != null) {
                endorseWildcards = (boolean)options[1];
            }
        }
    }

    String criteria = searchCriteria;
    if (endorseWildcards) {
        criteria = "(?i)" + searchCriteria.replace("?", ".?").replace("*", ".*?");
    }

    try {
        TableRowSorter<TableModel> sorter = new TableRowSorter<>(((DefaultTableModel) table.getModel()));
        sorter.setRowFilter(column < 0 ? RowFilter.regexFilter(criteria) : 
                            RowFilter.regexFilter(criteria, column));
        table.setRowSorter(sorter);
    }
    catch (Exception ex) {
        ex.printStackTrace();
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM