如何在 JTable java 中搜索元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22066387/
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
how to search an element in a JTable java?
提问by user3332136
I have made a JTable in java. I can do everything except search an element in my table. I want to work a input dialog so this is what I have at this moment:
我用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);
I thought to do it with a for loop. but I don't know how. Can someone help me pls?
我想用 for 循环来做。但我不知道怎么做。有人可以帮我吗?
回答by Levenal
The model of a JTable is where the data is held, by searching it you should be able to check if it contains what you want :
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
Good luck!
祝你好运!
回答by Not a bug
Here is an example of searching text from JTable
entered in JTextField
这是从JTable
输入中搜索文本的示例JTextField
Source : Filter table by the text in a TextField
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class RegexTable {
public static void main(String args[]) {
JFrame frame = new JFrame("Regexing JTable");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object rows[][] = { { "A", "About", 44.36 }, { "B", "Boy", 44.84 }, { "C", "Cat", 463.63 },
{ "D", "Day", 27.14 }, { "E", "Eat", 44.57 }, { "F", "Fail", 23.15 },
{ "G", "Good", 4.40 }, { "H", "Hot", 24.96 }, { "I", "Ivey", 5.45 },
{ "J", "Hyman", 49.54 }, { "K", "Kids", 280.00 } };
String columns[] = { "Symbol", "Name", "Price" };
TableModel model = new DefaultTableModel(rows, columns) {
public Class getColumnClass(int column) {
Class returnValue;
if ((column >= 0) && (column < getColumnCount())) {
returnValue = getValueAt(0, column).getClass();
} else {
returnValue = Object.class;
}
return returnValue;
}
};
final JTable table = new JTable(model);
final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
table.setRowSorter(sorter);
JScrollPane pane = new JScrollPane(table);
frame.add(pane, BorderLayout.CENTER);
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Filter");
panel.add(label, BorderLayout.WEST);
final JTextField filterText = new JTextField("A");
panel.add(filterText, BorderLayout.CENTER);
frame.add(panel, BorderLayout.NORTH);
JButton button = new JButton("Filter");
button.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));
}
}
});
frame.add(button, BorderLayout.SOUTH);
frame.setSize(300, 250);
frame.setVisible(true);
}
}
回答by Paul Samsotha
You probably want to use a RowFilter
to filter the search results. Below is an example using a RowFilter
and a DocumentListener
. When the user types, the rows are filter dynamically.
您可能希望使用 aRowFilter
来过滤搜索结果。下面是一个使用 aRowFilter
和 a的例子DocumentListener
。当用户键入时,行被动态过滤。
See RowFilterapi and DocumentListenerapi. If you don't like the dynamic filtering, you could just stick with the button, or you can add an ActionListener
to the the JTextField
, so when Enteris pressed, the filter will process. The code you would put in the listener call back (actionPerformed
) would just be
请参阅RowFilterapi 和DocumentListenerapi。如果你不喜欢动态筛选,你可以只坚持使用按钮,也可以添加一个ActionListener
到的JTextField
,所以当Enter被按下时,过滤器会处理。您将放入侦听器回调 ( actionPerformed
) 中的代码就是
String text = jtfFilter.getText();
if (text.trim().length() == 0) {
rowSorter.setRowFilter(null);
} else {
rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
}
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);
}
});
}
}
回答by Madhuka Dilhan
you can Search easily using this code
您可以使用此代码轻松搜索
Commons.attachJTableFilter(your_table_Variable_name, jtextfield_Variable_name);
回答by Kreator
Just a note If you getValueAt after sorting this will result the ORIGINAL row index. (which will be the wrong object) In that case you can use : JTable API
请注意,如果您在排序后 getValueAt 将导致原始行索引。(这将是错误的对象)在这种情况下,您可以使用:JTable API
table.convertRowIndexToModel (int indexAfterSorting) ;
This will Translate the sorted Row index into the original Row
这会将排序后的 Row 索引转换为原始 Row
回答by Madhuka Dilhan
you can use this class and call function using jtable variable and jtext field parameter should be pass to function. hope full and enjoy code
您可以使用此类并使用 jtable 变量调用函数,并且应将 jtext 字段参数传递给函数。希望完整并享受代码
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class FilterJtable {
public void FilterJtable(JTable jTable, JTextField jtfFilter) {
TableRowSorter<TableModel> rowSorter = new TableRowSorter<>(jTable.getModel());
jTable.setRowSorter(rowSorter);
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.
}
});
}
}
}