java 如何在 JTable 中实现搜索

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12123456/
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-10-31 07:39:49  来源:igfitidea点击:

How to implement Search in a JTable

javaswingsearchjtable

提问by aoulhent

I want to have a feature with JTable wherein I'll provide a textfield to enter a value to be searched from the JTable and if this entered value matches with any of the cell values in the JTable then that particular cell should be highlighted & the cell font should be turned to BOLD. The values will be matched when the user presses Enter key after specifying the value in the text field.

我想要 JTable 的一个功能,其中我将提供一个文本字段来输入要从 JTable 搜索的值,如果此输入值与 JTable 中的任何单元格值匹配,则应突出显示该特定单元格和单元格字体应该变成粗体。当用户在文本字段中指定值后按 Enter 键时,这些值将被匹配。

How can I do this?

我怎样才能做到这一点?

回答by aoulhent

This is a way to resolve the problem. Here is the code:

这是解决问题的一种方法。这是代码:

public class JTableSearchAndHighlight extends JFrame {

   private JTextField searchField;
   private JTable table;
   private JPanel panel;
   private JScrollPane scroll;

   public JTableSearchAndHighlight() {

     initializeInventory();
   }

private void initializeInventory() {

    panel = new JPanel();

    searchField = new JTextField();

    panel.setLayout(null);

    final String[] columnNames = {"Name", "Surname", "Age"};

    final Object[][] data = {{"Jhon", "Java", "23"}, {"Stupid", "Stupido", "500"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                            {"Max", "Dumbass", "10"}, {"Melanie", "Martin", "500"},
                            {"Jollibe", "Mcdonalds", "15"}};

    table = new JTable(data, columnNames);
    table.setColumnSelectionAllowed(true);
    table.setRowSelectionAllowed(true);

    scroll = new JScrollPane(table);
    scroll.setBounds(0, 200, 900, 150);

    searchField.setBounds(10, 100, 150, 20);
    searchField.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            String value = searchField.getText();

            for (int row = 0; row <= table.getRowCount() - 1; row++) {

                for (int col = 0; col <= table.getColumnCount() - 1; col++) {

                    if (value.equals(table.getValueAt(row, col))) {

                        // this will automatically set the view of the scroll in the location of the value
                        table.scrollRectToVisible(table.getCellRect(row, 0, true));

                        // this will automatically set the focus of the searched/selected row/value
                        table.setRowSelectionInterval(row, row);

                        for (int i = 0; i <= table.getColumnCount() - 1; i++) {

                            table.getColumnModel().getColumn(i).setCellRenderer(new HighlightRenderer());
                        }
                    }
                }
            }
        }
    });

    panel.add(searchField);
    panel.add(scroll);

    getContentPane().add(panel);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setTitle("Inventory Window");
    setSize(900, 400);
    setLocationRelativeTo(null);
    setVisible(true);
}

private class HighlightRenderer extends DefaultTableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

        // everything as usual
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

        // added behavior
        if(row == table.getSelectedRow()) {

            // this will customize that kind of border that will be use to highlight a row
            setBorder(BorderFactory.createMatteBorder(2, 1, 2, 1, Color.BLACK));
        }

        return this;
    }
}

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {

        public void run() {

            new JTableSearchAndHighlight();
        }
    });
  }
}

回答by Robin

The JXTablefrom the SwingX project has built-in support to search the table (look for the Searchableinterface). It also allows to quickly create a search field which uses this Searchableinterface: the JXSearchFieldand/or JXSearchPanel.

JXTable从SwingX项目已经内置支持查找表(查找Searchable接口)。它还允许快速创建使用此Searchable接口的搜索字段:JXSearchField和/或JXSearchPanel

If I remember correctly this will cover most of your requirements. Probably only need to add some custom code for making the cell contents bold

如果我没记错的话,这将涵盖您的大部分要求。可能只需要添加一些自定义代码来使单元格内容加粗