简体   繁体   中英

Filter JTable results with combobox

I have a table that is populated with data. I have a comboBox where the user should be able to select one of the choices, hit the filter button and the table would show the filtered results. I was attempting to use the tableRowSorter.setRowFilter method but cannot seem to figure out how it works. Would anybody mind explaining how the method works, or have any toher suggestions? Thanks

Read more about Sorting and Filtering in JTable . Here is simple example with RowFilter , examine that:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

public class Example extends JFrame {

    private JTable table;
    private DefaultTableModel model;
    private TableRowSorter<DefaultTableModel> sorter;

    public Example() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initComponents();
        pack();
        setVisible(true);

    }

    public static void main(String... strings) {
        new Example();
    }

    private void initComponents() {
        JPanel p = new JPanel();
        final JComboBox<String> box = new JComboBox<>(new String[]{"","1","2","3"});
        JButton b = new JButton("filter");
        b.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                RowFilter<DefaultTableModel, Object> rf  = RowFilter.regexFilter(box.getSelectedItem().toString(), 0);
                sorter.setRowFilter(rf);
            }
        });
        p.add(box);
        p.add(b);

        table = new JTable(model = new DefaultTableModel(3,3));
        sorter = new TableRowSorter<DefaultTableModel>(model);
        table.setRowSorter(sorter);

        add(p,BorderLayout.SOUTH);
        add(new JScrollPane(table));
    }
}

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