如何在JTable Java中搜索元素?

2022-09-03 16:24:35

我用java做了一个JTable。除了在表中搜索元素之外,我可以执行所有操作。我想处理一个输入对话框,所以这就是我现在所拥有的:

btnSearch = new JButton("Search");
    btnSearch.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {    
            String name = JOptionPane.showInputDialog("Wat wil je zoeken?");
        }
    });
    add(btnSearch);

我想用一个for循环来做。但我不知道该怎么做。有人可以帮我吗?


答案 1

您可能希望使用 来筛选搜索结果。下面是使用 a 和 a 的示例。当用户键入时,将动态筛选行。RowFilterRowFilterDocumentListener

请参阅 RowFilter api 和 DocumentListener api。如果您不喜欢动态过滤,则可以坚持使用按钮,也可以将添加到,这样当按下时,过滤器将处理。您放入侦听器回调 () 中的代码将只是ActionListenerJTextFieldEnteractionPerformed

  String text = jtfFilter.getText();
  if (text.trim().length() == 0) {
     rowSorter.setRowFilter(null);
  } else {
     rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
  }

enter image description here

import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class TestTableSortFilter extends JPanel {

    private String[] columnNames
            = {"Country", "Capital", "Population in Millions", "Democracy"};

    private Object[][] data = {
        {"USA", "Washington DC", 280, true},
        {"Canada", "Ottawa", 32, true},
        {"United Kingdom", "London", 60, true},
        {"Germany", "Berlin", 83, true},
        {"France", "Paris", 60, true},
        {"Norway", "Oslo", 4.5, true},
        {"India", "New Delhi", 1046, true}
    };

    private DefaultTableModel model = new DefaultTableModel(data, columnNames);
    private JTable jTable = new JTable(model);

    private TableRowSorter<TableModel> rowSorter
            = new TableRowSorter<>(jTable.getModel());

    private JTextField jtfFilter = new JTextField();
    private JButton jbtFilter = new JButton("Filter");

    public TestTableSortFilter() {
        jTable.setRowSorter(rowSorter);

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(new JLabel("Specify a word to match:"),
                BorderLayout.WEST);
        panel.add(jtfFilter, BorderLayout.CENTER);

        setLayout(new BorderLayout());
        add(panel, BorderLayout.SOUTH);
        add(new JScrollPane(jTable), BorderLayout.CENTER);

        jtfFilter.getDocument().addDocumentListener(new DocumentListener(){

            @Override
            public void insertUpdate(DocumentEvent e) {
                String text = jtfFilter.getText();

                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                String text = jtfFilter.getText();

                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
               JFrame frame = new JFrame("Row Filter");
               frame.add(new TestTableSortFilter());
               frame.pack();
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               frame.setLocationRelativeTo(null);
               frame.setVisible(true);
            }

        });
    }
}

答案 2

JTable的模型是保存数据的地方,通过搜索它,你应该能够检查它是否包含你想要的东西:

for(int i = 0; i < table.getRowCount(); i++){//For each row
    for(int j = 0; j < table.getColumnCount(); j++){//For each column in that row
        if(table.getModel().getValueAt(i, j).equals("STRING_TO_SEARCH")){//Search the model
            System.out.println(table.getModel().getValueAt(i, j));//Print if found string
        }
    }//For loop inner
}//For loop outer

祝你好运!


推荐