ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java – 搜索文本文件并在JPanel中显示结果

2019-10-01 17:02:03  阅读:182  来源: 互联网

标签:jtextpane java search file-io swing


有没有人对如何搜索文本文件并在JComponent中列出结果有任何想法,比如JPanel.

我一直试图让这项工作连续两天,但没有成功真的很感激回复.非常感谢提前.

我一直在尝试编写一个处理文本文件搜索查询的类.我的主要目标是在文本文件中获取包含在JTextField中输入的搜索关键字的行,并将其打印在适当的JComponent中(类似于JTextField,JTextPane,最适用的).

我希望搜索结果显示在谷歌搜索结果显示方式的列中,以便文本文件中的每一行都打印在自己的行中.我被告知最好使用ArrayList.我真的不知道该怎么做.我从各地获取了想法,这是我到目前为止所做的:

提前多多欣赏.我是Java的新手.我一整天都在努力做到这一点并且没有走得太远.我愿意尝试任何提供的东西,甚至是新方法.

// The class that handles the search query
// Notice that I've commented out some parts that show errors

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JTextPane;


public class Search {

    public static String path;
    public static String qri;

    public Search(String dTestFileDAT, String qry) {
        path = dTestFileDAT;
        qri = qry;
    }

    public static JTextPane resultJTextPane;
    public static List<String> linesToPresent = new ArrayList<String>();

    public static List<String> searchFile(String path, String match){

        File f = new File(path);
        FileReader fr;
        try {
            fr = new FileReader(f);
            BufferedReader br = new BufferedReader(fr);
            String line;
                do{
                    line = br.readLine();
                    Pattern p = Pattern.compile(match);
                    Matcher m = p.matcher(line);
                    if(m.find())
                        linesToPresent.add(line);
                } while(line != null);

                br.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // resultJTextPane = new JTextPane();
        // resultJTextPane = (JTextPane) Home.BulletinsJPanel.add(linesToPresent);

        return linesToPresent;
    }
}

// This handles the click event to take the query. Notice that I've commented out some parts that show errors
private void mouseClickedSearch(java.awt.event.MouseEvent evt) {
    Search fs = new Search("/D:/TestFile.dat/", "Text to search for");

    // searchResultsJPanel.add(Search.searchFile("/D:/TestFile.dat/", "COLE"));
    // searchResultsJTextField.add(fs);
}

解决方法:

有许多可能的解决方案,这只是一个简单的解决方案(不严肃,它是;))

基本上,这只是使用JList来存储搜索文件中搜索文本的所有匹配项.

这是一个区分大小写的搜索,所以要小心

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MySearch {

    public static void main(String[] args) {
        new MySearch();
    }

    public MySearch() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JTextField findText;
        private JButton search;
        private DefaultListModel<String> model;

        public TestPane() {
            setLayout(new BorderLayout());
            JPanel searchPane = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.insets = new Insets(2, 2, 2, 2);
            searchPane.add(new JLabel("Find: "), gbc);
            gbc.gridx++;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1;
            findText = new JTextField(20);
            searchPane.add(findText, gbc);

            gbc.gridx++;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            search = new JButton("Search");
            searchPane.add(search, gbc);

            add(searchPane, BorderLayout.NORTH);

            model = new DefaultListModel<>();
            JList list = new JList(model);
            add(new JScrollPane(list));

            ActionHandler handler = new ActionHandler();

            search.addActionListener(handler);
            findText.addActionListener(handler);
        }

        public class ActionHandler implements ActionListener {

            @Override
            public void actionPerformed(ActionEvent e) {
                model.removeAllElements();
//                    BufferedReader reader = null;

                String searchText = findText.getText();
                try (BufferedReader reader = new BufferedReader(new FileReader(new File("search.txt")))) {

                    String text = null;
                    while ((text = reader.readLine()) != null) {

                        if (text.contains(searchText)) {

                            model.addElement(text);

                        }

                    }

                } catch (IOException exp) {

                    exp.printStackTrace();
                    JOptionPane.showMessageDialog(TestPane.this, "Could not create file", "Error", JOptionPane.ERROR_MESSAGE);

                }
            }
        }
    }
}

你也可以采取另一种机智,只是突出显示比赛…

这使用了略有不同的方法,因为这是交互式的.基本上你只需键入,等待1/4秒,它将开始搜索…

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

public class MySearch02 {

    public static void main(String[] args) {
        new MySearch02();
    }

    public MySearch02() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JTextField findText;
        private JTextArea ta;
        private Timer keyTimer;

        public TestPane() {
            setLayout(new BorderLayout());
            JPanel searchPane = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.insets = new Insets(2, 2, 2, 2);
            searchPane.add(new JLabel("Find: "), gbc);
            gbc.gridx++;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1;
            findText = new JTextField(20);
            searchPane.add(findText, gbc);

            add(searchPane, BorderLayout.NORTH);

            ta = new JTextArea(20, 40);
            ta.setWrapStyleWord(true);
            ta.setLineWrap(true);
            ta.setEditable(false);
            add(new JScrollPane(ta));

            loadFile();

            keyTimer = new Timer(250, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String find = findText.getText();
                    Document document = ta.getDocument();
                    try {
                        for (int index = 0; index + find.length() < document.getLength(); index++) {
                            String match = document.getText(index, find.length());
                            if (find.equals(match)) {
                                javax.swing.text.DefaultHighlighter.DefaultHighlightPainter highlightPainter =
                                        new javax.swing.text.DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
                                ta.getHighlighter().addHighlight(index, index + find.length(),
                                        highlightPainter);
                            }
                        }
                    } catch (BadLocationException exp) {
                        exp.printStackTrace();
                    }
                }
            });
            keyTimer.setRepeats(false);

            findText.getDocument().addDocumentListener(new DocumentListener() {
                @Override
                public void insertUpdate(DocumentEvent e) {
                    keyTimer.restart();
                }

                @Override
                public void removeUpdate(DocumentEvent e) {
                    keyTimer.restart();
                }

                @Override
                public void changedUpdate(DocumentEvent e) {
                    keyTimer.restart();
                }
            });
        }

        protected void loadFile() {
            String searchText = findText.getText();
            try (BufferedReader reader = new BufferedReader(new FileReader(new File("search.txt")))) {
                ta.read(reader, "Text");
            } catch (IOException exp) {
                exp.printStackTrace();
                JOptionPane.showMessageDialog(TestPane.this, "Could not create file", "Error", JOptionPane.ERROR_MESSAGE);
            }
            ta.setCaretPosition(0);
        }
    }
}

标签:jtextpane,java,search,file-io,swing
来源: https://codeday.me/bug/20191001/1839236.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有