如何使用jtextfield在jtable中搜索数据? [英] how to search data in jtable using jtextfield?

查看:98
本文介绍了如何使用jtextfield在jtable中搜索数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在netbeans中创建jtable并在jtable中填充数据库中的数据,但我无法使用jtextfield在jtable中实现搜索选项。任何人都可以指导我。
谢谢

I create jtable in netbeans and populate data from database in jtable, but i am unable to implement search option in jtable using jtextfield. Can anyone please guide me. Thanks

推荐答案

为了在桌子上搜索某些东西,你必须将原始内容存储在某个变量中。下面的示例我将表模型的初始值存储到向量中。

下面有两个实现。一旦在textfield上键入内容就会进行搜索,而只有在单击按钮后才进行搜索。

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.

对于第一个,您必须使用 documentListener 为你做的事情。

For the first one you have to use a documentListener to do things for you.

以下函数将删除表值[如果找不到匹配表,则表格将为在所有单元格中搜索字符串,如果找到匹配项,则会将该行添加到表格中。

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;
            }
        }

    }
}

这是以上的完整代码

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                   
}

这篇关于如何使用jtextfield在jtable中搜索数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆