2013-08-01 38 views
5

Có ai có bất kỳ ý tưởng nào về cách tôi có thể tìm kiếm tệp văn bản và liệt kê kết quả trong JComponent, như JPanel hay không.Tìm kiếm tệp văn bản và kết quả hiển thị trong JPanel

Tôi đã cố gắng thực hiện công việc này trong hai ngày nay, nhưng không thành công nào thực sự đánh giá cao câu trả lời. Cảm ơn rất nhiều trước.

Tôi đã cố gắng viết một lớp xử lý truy vấn tìm kiếm vào tệp văn bản. Mục tiêu chính của tôi là lấy các dòng trong một tệp văn bản chứa các từ khóa tìm kiếm được nhập vào một JTextField và in chúng ra trong một JComponent thích hợp (một cái gì đó giống như một JTextField, JTextPane, tùy theo điều kiện nào phù hợp nhất).

Tôi muốn kết quả tìm kiếm hiển thị trong các cột như cách hiển thị kết quả tìm kiếm của google, sao cho mỗi dòng từ tệp văn bản được in theo dòng riêng của nó. Tôi đã nói rằng tốt nhất là sử dụng một ArrayList. Tôi thực sự không biết làm thế nào để làm điều này. Tôi đã chọn các ý tưởng từ khắp nơi và đây là những gì tôi có cho đến thời điểm này:

Đánh giá cao trước. Tôi rất mới với Java. Tôi đã ở đó cả ngày cố gắng để có được quyền này và đã không đi xa. Sẵn sàng thử mọi thứ được cung cấp, ngay cả một cách tiếp cận mới.

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

* "Có ai có bất kỳ ý tưởng về làm thế nào tôi có thể tìm kiếm một tập tin văn bản và liệt kê các kết quả trong JComponent, như JPanel? * "- Có - [Bạn đã thử gì?] (http://mattgemmell.com/2008/12/08/what-have-you-tried/) Có lẽ chúng ta có thể đưa ra một số hướng – MadProgrammer

+0

Bạn đã cố gắng thực hiện công việc này trong hai ngày, vì vậy chắc chắn bạn có một số mã bạn có thể chỉ cho chúng tôi? Một số điểm khởi đầu? Hãy xem nó. – Kon

+0

@olicver muchai xem JTextPane.read() – mKorbel

Trả lời

8

Có một số giải pháp khả thi, đây chỉ là một trong những đơn giản (không nghiêm túc, đó là;))

Về cơ bản, điều này chỉ sử dụng một JList để lưu trữ tất cả các trận đấu của các văn bản tìm kiếm từ tệp tìm kiếm.

Đây là một trường hợp tìm kiếm nhạy cảm, vì vậy hãy cẩn thận

enter image description here

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

       } 
      } 
     } 
    } 
} 

Bạn cũng có thể kéo dài sự khéo léo khác và chỉ cần đánh dấu các trận đấu ...

enter image description here

sử dụng này một cách tiếp cận hơi khác nhau vì điều này là tương tác. Về cơ bản bạn chỉ cần gõ, chờ một 1/4 giây và nó sẽ bắt đầu tìm kiếm ...

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

excelent ........... – mKorbel

+0

@mKorbel Bạn nghĩ tôi là người lên máy bay hoặc thứ gì đó ;) – MadProgrammer

+0

:-) bạn là người lên máy bay hoặc một cái gì đó, phaaaa không phải tôi không có vấn đề để gọi những thứ với tên riêng của nó – mKorbel

0

Hãy thử điều này:

import java.awt.BorderLayout; 
import java.awt.Component; 
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 java.io.InputStreamReader; 
import java.util.StringJoiner; 
import javax.swing.DefaultListCellRenderer; 
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 SearchTextFile { 

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

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

      JFrame frame = new JFrame("Bible Search"); 
      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; 
    private JList list; 

    private String searchPhrase; 

    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<>(); 
     list = new JList(model); 
     list.setCellRenderer(new HighlightListCellRenderer()); 
     add(new JScrollPane(list)); 

     ActionHandler handler = new ActionHandler(); 

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

     try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/Script.txt")))) { 

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

     } catch (IOException exp) { 

      exp.printStackTrace(); 

     } 
    } 

    public class ActionHandler implements ActionListener { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      searchPhrase = findText.getText(); 
      if (searchPhrase != null && searchPhrase.trim().length() == 0) { 
       searchPhrase = null; 
      } 
      list.repaint(); 
//    model.removeAllElements(); 
////     BufferedReader reader = null; 
// 
//    String searchText = findText.getText(); 
//    try (BufferedReader reader = new BufferedReader(new FileReader(new File("bible.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, "Something Went  Wrong", "Error", JOptionPane.ERROR_MESSAGE); 
// 
//    } 
     } 
    } 

     public class HighlightListCellRenderer extends DefaultListCellRenderer { 

     public final String WITH_DELIMITER = "((?<=%1$s)|(?=%1$s))"; 

     @Override 
     public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { 
      if (value instanceof String && searchPhrase != null) { 
       String text = (String) value; 
       if (text.contains(searchPhrase)) { 
        text = text.replace(" ", "&nbsp;"); 
        value = "<html>" + text.replace(searchPhrase, "<font color=#ffff00>" + searchPhrase + "</font>") + "</html>"; 
       } 
      } 
      return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //To change body of generated methods, choose Tools | Templates. 
     } 

    } 
} 
} 
Các vấn đề liên quan