搜索文本文件并在JPanel中显示结果 [英] Search text file and display results in a JPanel

查看:157
本文介绍了搜索文本文件并在JPanel中显示结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人有任何想法,我怎么可以搜索一个文本文件,并列出JComponent的结果,如JPanel。



我一直在努力这工作了两天了,但没有成功,真的会很感激答复。非常感谢。



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



我希望搜索结果以列的形式显示,例如google搜索结果的显示方式,以便文本文件中的每一行都按照自己的行打印。我被告知最好使用ArrayList。我真的不知道该怎么做。我已经从各地拿起了一些想法,这就是我迄今为止的想法:

提前获得了很多赞赏。我对Java很陌生。我一整天都在努力做到这一点,并没有走得太远。我们愿意尝试提供的任何东西,甚至是一种新的方法。

  //处理搜索查询的类
/ /注意我已经注释了一些显示错误的部分

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){

文件f = new File(path);
FileReader fr;
尝试{
fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
字符串行;
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自动生成的catch块
e.printStackTrace();
}

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

返回linesToPresent;
}
}

//这将处理click事件以进行查询。请注意,我已经注释了一些显示错误的部分
private void mouseClickedSearch(
Search fs = new Search(/ D:/TestFile.dat/ ,要搜索的文本);

// 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){$ b $ new MySearch();

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

JFrame框架= 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;
私人JButton搜索;
private DefaultListModel< String>模型;

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 {
$ b $ @Override
public void actionPerformed(ActionEvent e){
model.removeAllElements() ;
// BufferedReader reader = null;

字符串searchText = findText.getText();
try(BufferedReader reader = new BufferedReader(new FileReader(new File(search.txt)))){

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

if(text.contains(searchText)){

model.addElement文本);



$ b $ catch(IOException exp){

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





code $ pre

您也可以采取另一种方法,只需突出显示匹配...


这是一个稍微不同的方法,因为这是交互式的。基本上,你只需输入,等待1/4秒,它会开始搜索...
$ b $ pre $ 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){
MySearch02();

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

JFrame框架= 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;
私人定时器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();
(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();

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

@覆盖
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);
}
}
}


Does anyone have any ideas on how I can search a text file and list the results in a JComponent, like a JPanel.

I've been trying to make this work out for two days now, but no success will really appreciate a reply. Thanks a lot in advance.

I've been trying to write a class that handles search queries to a text file. My main goal is to get the lines in a text file that contain the search keywords entered in a JTextField and print them out in an appropriate JComponent(something like a JTextField, JTextPane, whichever best applicable).

I'd like the search results to show in columns like how google search results get displayed, so that each line from the text file gets printed in its own line. I've been told that it's best to use an ArrayList. I really don't know how to do this. I've picked up ideas from all over and this is what I have so far:

Much appreciation in advance. I am very new to Java. I've been at it the whole day trying to get this right and have not gone any far. Am willing to try anything offered, even a new approach.

// 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);
}

解决方案

There are a number of possible solutions, this is just a simple one (no seriously, it is ;))

Basically, this just uses a JList to store all the matches of the search text from the search file.

This is a case sensitive search, so beware

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);

                }
            }
        }
    }
}

You could also take another tact and simply highlight the matches...

This uses a slightly different approach as this is interactive. Basically you simply type, wait a 1/4 second and it will start searching...

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);
        }
    }
}

这篇关于搜索文本文件并在JPanel中显示结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆