[英]Select A row from Jtable based on Jtextfield Input
I have a JTable displaying contents in this format: 我有一个JTable以这种格式显示内容:
Part Number Quantity Price
SD1131 7 1,000
SD6534 6 2,000
On the same frame I have a JTextfield(txtNo). 在同一帧上,我有一个JTextfield(txtNo)。 I need it such that when the user types the Part Number on the JTextfield, the corresponding record is selected on the JTable.
我需要它,以便当用户在JTextfield上键入部件号时,在JTable上选择相应的记录。 So far I have only been able to select records based on the row number like this:
到目前为止,我只能根据这样的行号选择记录:
txtNo.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
int index1 = 0;
int index2 = 0;
try {
index1 = Integer.valueOf(txtNo.getText());
tbStore.setRowSelectionInterval(index2, index1);
} catch (Exception ae) {
ae.printStackTrace();
}
}
});
How can I implement the same method to select the JTable row based on the input of the JTextfield? 如何实现相同的方法来基于JTextfield的输入选择JTable行?
You will need to find the item in your table for which the part number is equal to the part number entered in the textfield. 您将需要在表中找到零件编号等于在文本字段中输入的零件编号的项目。 Steps to take:
采取的步骤:
TableModel
TableModel
搜索匹配元素的索引 JTable
using the convertRowIndexToView
method (to take in account sorting, filtering, ... ) convertRowIndexToView
方法将该索引转换为JTable
的相应行索引(以考虑排序,过滤等)。 setRowSelectionInterval
method of the JTable
to select that row JTable
的setRowSelectionInterval
方法选择该行 As an alternative, you can use the JXTable
of the SwingX project which has searching capabilities built-in. 或者,您可以使用SwingX项目的
JXTable
,它具有内置的搜索功能。 The SwingX library also includes a component which allows to search such a JXTable
(see JXSearchPanel
and JXSearchField
) SwingX库还包括一个允许搜索这样的
JXTable
(请参见JXSearchPanel
和JXSearchField
)
You should interrogate the TableModel and find out which row contains the part number you are looking for: 您应该查询TableModel并找出哪一行包含您要查找的零件号:
for(int i=0;i<tbStore.getRowCount();i++) {
// 0 is for the column Part number
if(tbStore.getValueAt(i, 0).equals(Integer.valueOf(txtNo.getText())) {
tbStore.setRowSelectionInterval(i, i);
break;
}
}
Caveats: I haven't tested this code, but it should give you at least the basic idea. 注意事项:我尚未测试此代码,但它至少应该给您基本概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.