简体   繁体   English

根据Jtextfield输入从Jtable中选择一行

[英]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: 采取的步骤:

  • Read the contents of your textfield 阅读您的文本字段的内容
  • Search the index of the matching element in the TableModel TableModel搜索匹配元素的索引
  • Convert that index to the corresponding row index in the JTable using the convertRowIndexToView method (to take in account sorting, filtering, ... ) 使用convertRowIndexToView方法将该索引转换为JTable的相应行索引(以考虑排序,过滤等)。
  • Use the setRowSelectionInterval method of the JTable to select that row 使用JTablesetRowSelectionInterval方法选择该行

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 (请参见JXSearchPanelJXSearchField

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM