简体   繁体   English

如何使用 jtextfield 在 jtable 中搜索数据?

[英]how to search data in jtable using jtextfield?

I create jtable in netbeans and populate data from database in jtable, but i am unable to implement search option in jtable using jtextfield.我在 netbeans 中创建 jtable 并在 jtable 中填充数据库中的数据,但我无法使用 jtextfield 在 jtable 中实现搜索选项。 Can anyone please guide me.任何人都可以请指导我。 Thanks谢谢

In order to search something on table you have to have original content stored in some variable.In the below example I stored the initial values of table model to a vector.为了在表上搜索某些内容,您必须将原始内容存储在某个变量中。在下面的示例中,我将表模型的初始值存储到向量中。
There are two implementations below.One to search as soon as you type something on textfield, other to search only after a button is clicked.下面有两种实现。一种是在文本字段上输入内容后立即搜索,另一种是仅在单击按钮后进行搜索。

For the first one you have to use a documentListener to do things for you.对于第一个,您必须使用documentListener为您做事。

The below function will remove the table values[incase if no match found the table will be empty] and search for a string in all cells and if a match is found it will add that row to the table.下面的函数将删除表格值[如果没有找到匹配项,表格将为空]并在所有单元格中搜索一个字符串,如果找到匹配项,它将将该行添加到表格中。

public void searchTableContents(String searchString) {    
  DefaultTableModel currtableModel = (DefaultTableModel) table.getModel();
    //To empty the table before search
    currtableModel.setRowCount(0);
    //To search for contents from original table content
    for (Object rows : originalTableModel) {
        Vector rowVector = (Vector) rows;
        for (Object column : rowVector) {
            if (column.toString().contains(searchString)) {
                //content found so adding to table
                currtableModel.addRow(rowVector);
                break;
            }
        }

    }
}

This is the fullcode of the above这是上面的完整代码

import java.util.Vector;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;

public class TableSearch extends javax.swing.JFrame {
Vector originalTableModel;
DocumentListener documentListener;

public TableSearch() {
    initComponents();
    setLocationRelativeTo(null);
    //backup of original values to check
    originalTableModel = (Vector) ((DefaultTableModel) table.getModel()).getDataVector().clone();
    //add document listener to jtextfield to search contents as soon as something typed on it
    addDocumentListener();
}

private void addDocumentListener() {
    documentListener = new DocumentListener() {
        public void changedUpdate(DocumentEvent documentEvent) {
            search();
        }

        public void insertUpdate(DocumentEvent documentEvent) {
            search();
        }

        public void removeUpdate(DocumentEvent documentEvent) {
            search();
        }

        private void search() {
            searchTableContents(jTextField1.getText());
        }
    };
    searchOnType.setSelected(true);
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    table = new javax.swing.JTable();
    jPanel1 = new javax.swing.JPanel();
    searchOnType = new javax.swing.JCheckBox();
    jTextField1 = new javax.swing.JTextField();
    searchButton = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    table.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {"masd", "asdad", "asdasda", "ert"},
            {"gdfg", "name", "test", "dfg"},
            {"rrrh", "dfg", "sdfsf", "sdf"},
            {"ter", "retg", "wersd", "wer"}
        },
        new String [] {
            "Title 1", "Title 2", "Title 3", "Title 4"
        }
    ));
    jScrollPane1.setViewportView(table);

    getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

    searchOnType.setText("Search on Type");
    searchOnType.addItemListener(new java.awt.event.ItemListener() {
        public void itemStateChanged(java.awt.event.ItemEvent evt) {
            searchOnTypeItemStateChanged(evt);
        }
    });

    searchButton.setText("Search");
    searchButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            searchButtonActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(searchButton)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(searchOnType)
            .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(searchButton)
                .addComponent(searchOnType))
            .addContainerGap())
    );

    getContentPane().add(jPanel1, java.awt.BorderLayout.NORTH);

    pack();
}// </editor-fold>                        

private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
    searchTableContents(jTextField1.getText());
}                                            

private void searchOnTypeItemStateChanged(java.awt.event.ItemEvent evt) {                                              
    if (searchOnType.isSelected()) {
        jTextField1.getDocument().addDocumentListener(documentListener);
    } else {
        jTextField1.getDocument().addDocumentListener(null);
    }
}                                             

public void searchTableContents(String searchString) {
    DefaultTableModel currtableModel = (DefaultTableModel) table.getModel();
    //To empty the table before search
    currtableModel.setRowCount(0);
    //To search for contents from original table content
    for (Object rows : originalTableModel) {
        Vector rowVector = (Vector) rows;
        for (Object column : rowVector) {
            if (column.toString().contains(searchString)) {
                //content found so adding to table
                currtableModel.addRow(rowVector);
                break;
            }
        }

    }
}

public static void main(String args[]) {
    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new TableSearch().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField1;
private javax.swing.JButton searchButton;
private javax.swing.JCheckBox searchOnType;
private javax.swing.JTable table;
// End of variables declaration                   
}

I create jtable with one column in eclipse and populate data from database in jtable.我在 eclipse 中用一列创建 jtable,并在 jtable 中填充数据库中的数据。 If Two Textfield in frame and I enter something in Textfield1 and it will highlight those rows in table that matches the text and those highlight row selected in jtable value show in Textfield1.如果框架中有两个 Textfield 并且我在 Textfield1 中输入了一些内容,它将突出显示表中与文本匹配的那些行,以及在 Textfield1 中显示的 jtable 值中选择的那些突出显示行。 And Same happen in Textfield2 at same form.同样在 Textfield2 中以相同的形式发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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