Java 按 JTextField 值过滤 JTable 行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19364436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:30:34  来源:igfitidea点击:

JTable Row filtering by JTextField value

javaswingjtablejtextfieldrowfilter

提问by Sajad

I enter a name on my JTextfield , But my table don't filter any thing!

我在我的 JTextfield 上输入了一个名字,但我的表不过滤任何东西!

My code:

我的代码:

public class UserPage_Admin extends JFrame {

JTable table;
UserModel model;
public UserPage_Admin() {

    model = new UserModel(...);
    TableRowSorter sorter = new TableRowSorter<TableModel>(model);
    table = new JTable(model);
    table.setRowSorter(sorter);

    add(new JScrollPane(table), BorderLayout.CENTER);
    add(panelForm(), BorderLayout.PAGE_START);

    RowFilter<UserModel, Object> rf = null;
    try {
        rf = RowFilter.regexFilter(filterTF.getText(), 0);
    } catch (PatternSyntaxException pse) {
        return;
    }
    sorter.setRowFilter(rf);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(850, 600);
    setVisible(true);
}

采纳答案by Sage

you are calling RowFilter.regexFilter(filterTF.getText(), 0);in UserPage_Admin()constructor. How it supposed to read the textfrom the filterTF. I think you should call it from an Action Event Listener assigned to a JButtonwhich will be called upon submitting(clicking) the text as follows:

RowFilter.regexFilter(filterTF.getText(), 0);UserPage_Admin()构造函数中调用。它应该如何从 filterTF读取文本。我认为您应该从分配给 a 的 Action Event Listener 调用它JButton,它将在提交(单击)文本时调用,如下所示:

submitButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        String text = filterText.getText();
        if (text.length() == 0) {
          sorter.setRowFilter(null);
        } else {
          sorter.setRowFilter(RowFilter.regexFilter(text, 0));
        }
      }
    }); 

If you want to use Filtering upon user key type event, add key listenerto the text field you are taking input filter-string.

如果要对用户键类型事件使用过滤,请将键侦听器添加到要输入过滤器字符串的文本字段。

filterTxtFeild.addKeyListener(new KeyAdapter() {
            public void keykeyReleased(KeyEvent evt) {
              // on each key type event filter. 
             // put your filter code as submit button
            }
        });

However, as it is suggested in the comments below, to work with Swing Text Component, one should have used the Document.addDocumentListener(DocumentListener). A Swing text component uses a Documentto represent its content. Document events occur when the content of a document changes in any way. Add the document listener as follows:

但是,正如下面的评论中所建议的那样,要使用 Swing 文本组件,应该使用Document.addDocumentListener(DocumentListener). Swing 文本组件使用Document来表示其内容。当文档的内容以任何方式发生变化时,就会发生文档事件。添加文档监听器如下:

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

      @Override
      public void insertUpdate(DocumentEvent e) {
        // put your filter code here upon data insertion
      }

      @Override
      public void removeUpdate(DocumentEvent e) 
      { 
            //put your filter code here upon data removal
      }

      @Override
      public void changedUpdate(DocumentEvent e) {}
    });

Edit: Why DocumentListener is preferable ?

编辑:为什么 DocumentListener 更可取?

If we want validation of input in the data source, using KeyEventwhile filtering the data you'll find it does not reflect the user's keystroke and input events are sent to the listeners before they are processed by the data source. suppose that when we want an user nameto be entered, someone input a text like "$%^&". On such invalid input, KeyEventwill still be fired even though no valid changes has been made to data source. But, DocumentListenersare notified only when a valid changes has been made to the data source. Data entry components produce events in which a validatorcan listen for asynchronously, one should never modify the contentsof a text component from within a DocumentListener. If we do so, the program will likely deadlock.

如果我们想要验证数据源中的输入,使用KeyEventwhile 过滤数据,您会发现它不会反映用户的击键,并且输入事件在数据源处理之前被发送到侦听器。假设当我们想要user name输入an 时,有人输入了像"$%^&". 在这样的无效输入上,KeyEvent即使没有对数据源进行有效的更改,仍然会被触发。但是,DocumentListeners只有在对数据源进行有效更改时才会收到通知。数据输入组件制造在一个事件validator可以监听asynchronously,一个人永远不能修改其内容从内部的文本组件DocumentListener。如果我们这样做,程序很可能会死锁。

回答by Lorenzo Gatti

You simply fail to use sorterafter initializing it. You should call JTable.setRowSorter().

初始化后,您只是无法使用分拣机。您应该调用JTable.setRowSorter()

回答by mKorbel

I enter a name on my JTextfield , But my table don't filter any thing!

我在我的 JTextfield 上输入了一个名字,但我的表不过滤任何东西!

  • there are two ways, you don't mentioned expected logics

    1. filtering on KeyTyped from DocumentListener (your code talking about ???)

    2. from ActionListener invoked from ENTER Key

  • both a.m. ways added to JTextField

  • 有两种方法,你没有提到预期的逻辑

    1. 从 DocumentListener 对 KeyTyped 进行过滤(您的代码在谈论 ???)

    2. 来自从 ENTER 键调用的 ActionListener

  • 两种方式都添加到 JTextField



  • then there are another two very important options

    1. filtering in whole JTables, columns and rows (your code talking about ???)

    2. in one (quite possible in two or more, never tried) columns

  • 然后还有另外两个非常重要的选项

    1. 过滤整个 JTables、列和行(你的代码在谈论 ???)

    2. 在一列(很可能在两列或更多列中,从未尝试过)



  • everything depends of your goal

  • everything by using standard methods implemented in API

  • 一切都取决于你的目标

  • 一切都使用在 API 中实现的标准方法