使用JTextField进行JTable过滤不起作用 [英] JTable filtering with JTextField doesn't work
问题描述
我有一个JTable(DefaultTableModel)和一个JTextField.我想用输入文本字段的正则表达式过滤JTable.启动程序时,将显示所有条目,但是当我在文本字段中输入文本时,即使应该在一行中找到文本,也不会显示任何行.
I have a JTable (DefaultTableModel) and a JTextField. I'd like to filter the JTable with the regex I put into the text field. When I start the program, all entries are shown, but when I enter text into the text field, no rows are displayed even though it should find the text within a row.
private void createFilter() {
_sorter = new TableRowSorter<DefaultTableModel>(new DefaultTableModel());
JPanel filterPanel = new JPanel();
filterPanel.setLayout(new BorderLayout());
JLabel filterLabel = new JLabel("Filter:");
filterPanel.add(filterLabel, BorderLayout.WEST);
_inputField = new JTextField();
_inputField.setColumns(40);
filterPanel.add(_inputField, BorderLayout.CENTER);
_inputField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent de) {
newFilter();
}
public void removeUpdate(DocumentEvent de) {
newFilter();
}
public void changedUpdate(DocumentEvent de) {
newFilter();
}
});
JButton clearButton = new JButton("X");
clearButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
_inputField.setText("");
}
});
filterPanel.add(clearButton, BorderLayout.EAST);
_mainFrame.add(filterPanel, BorderLayout.SOUTH);
}
private void newFilter() {
RowFilter<DefaultTableModel, Object> rowFilter = null;
try {
rowFilter = RowFilter.regexFilter(_inputField.getText());
}
catch(java.util.regex.PatternSyntaxException ex) {
return;
}
_sorter.setRowFilter(rowFilter);
_table.setRowSorter(_sorter);
}
我的调试器告诉我,rowFilter已初始化,因此不可能是因为RegEx错误.此外,每次击键都会调用newFilter().
My debugger shows me, that rowFilter is initialized, so it can't be because of a wrong RegEx. Also newFilter() is called at every keystroke.
先谢谢了.如果需要,我很乐意提供更多信息.
Thanks in advance. I'd be happy to provide more information if needed.
此致, 迈克尔
推荐答案
似乎JTable和TableRowSorter各自具有不同的表模型.应该使用JTable的表模型构造TableRowSorter.
It seems that the JTable and the TableRowSorter each have a different table model. The TableRowSorter should be constructed with the table model of the JTable.
这篇关于使用JTextField进行JTable过滤不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!