HighLishg search text in JTable

Hi, I want to search for particular words in JTable, I am able to search for JTextComponent using HighLighter ,
same way I convered my all data of JTable to JTextComponent, but Its failing to give the Index text.indexOf(pattern, pos)(where text is my JTextComponent , pattern is my search word, and pos is 0 initial),
below is the code,
public void highlight(JTextComponent textComp, String pattern) {
          // First remove all old highlights
          removeHighlights(textComp);
          try {
                Highlighter hilite = textComp.getHighlighter();
               Document doc = textComp.getDocument();
               String text = doc.getText(0, doc.getLength());
               int pos = 0;
               System.out.println(text);
               System.out.println(pattern);
               System.out.println(text.indexOf(pattern, pos));
               // Search for pattern
               while ((pos = text.indexOf(pattern, pos)) >= 0) {
                    // Create highlighter using private painter and apply around
                    // pattern
                    hilite.addHighlight(pos, pos + pattern.length(),
                              myHighlightPainter);
                    pos += pattern.length();
          } catch (BadLocationException e) {
     public void highlight(JTable table, String pattern) {
          // First remove all old highlights
          try {
               //calling table
                table.setModel(new javax.swing.table.DefaultTableModel(
                        new Object [][] {
                           {"One two three four"},
                           {"Uno dos tres quatro"},
                           {"Odin dva tri chetire"},
                           {"1111 2222 3333 4444 One"}
                        new String [] {
                           "Strings"
                        Class[] types = new Class [] {
                           java.lang.String.class
                        public Class getColumnClass(int columnIndex) {
                           return types [columnIndex];
               int numRows = table.getRowCount();
              int numCols = table.getColumnCount();
              javax.swing.table.TableModel model = table.getModel();
              JTextComponent textComp = null;
              for (int i = 0; i < numRows; i++) {
              for (int j = 0; j < numCols; j++) {
                   System.out.print(" " + model.getValueAt(i, j));
                   DefaultCellEditor ed = (DefaultCellEditor)table.getCellEditor(i,j);
                   textComp = (JTextComponent)ed.getComponent();
              removeHighlights(textComp);
              Highlighter hilite = textComp.getHighlighter();
               Document doc = textComp.getDocument();
               String text = doc.getText(0, doc.getLength());
               int pos = 0;
               System.out.println(text);
               System.out.println(pattern);
               System.out.println(text.indexOf(pattern, pos));
               // Search for pattern
               while ((pos = text.indexOf(pattern, pos)) >= 0) {
                    // Create highlighter using private painter and apply around
                    // pattern
                    hilite.addHighlight(pos, pos + pattern.length(),
                              myHighlightPainter);
                    pos += pattern.length();
          } catch (BadLocationException e) {
     } It will really help if nay one find why its giving -1 for index.
Thanks
Srikanth

below is the solution
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellRenderer;
import javax.swing.text.DefaultHighlighter;
public class TableCellRendererBug extends JFrame {
     private boolean DEBUG = false;
     public TableCellRendererBug() {
          super("TableCellRendererBug");
          Object[][] data = { { "Jay Four Four Jay", "Four" }, { "Jay", "Jay" }, };
          String[] columnNames = { "Column 1", "Column 2" };
          JTable table = new JTable(data, columnNames);
          table.setPreferredScrollableViewportSize(new Dimension(200, 50));
          // Create the scroll pane and add the table to it.
          JScrollPane scrollPane = new JScrollPane(table);
          table.setDefaultRenderer(Object.class, new CellHighlightRenderer());
          System.out.println(table.getColumnClass(0).toString());
          // Add the scroll pane to this window.
          getContentPane().add(scrollPane, BorderLayout.CENTER);
          addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent e) {
                    System.exit(0);
     class CellHighlightRenderer extends JTextField implements TableCellRenderer {
          public DefaultHighlighter high = new DefaultHighlighter();
          public DefaultHighlighter.DefaultHighlightPainter highlight_painter = new DefaultHighlighter.DefaultHighlightPainter(
                    new Color(198, 198, 250));
          public CellHighlightRenderer() {
               setBorder(BorderFactory.createEmptyBorder());
               setHighlighter(high);
          public Component getTableCellRendererComponent(JTable table,
                    Object value, boolean isSelected, boolean hasFocus, int row,
                    int column) {
               setFont(table.getFont());
               setValue(value);
               int len = getText().length();
               int first = (row & 1) + 1;
               int last = (row & 1) + first + 1;
               int pos =0;
               String pattern="Jay";
               //if (len > last) {
               while ((pos = value.toString().indexOf(pattern, pos)) >= 0) {
                    try {
                         //high.addHighlight(first, last, highlight_painter);
                         high.addHighlight(pos, pos + pattern.length(), highlight_painter);
                         pos += pattern.length();
                    } catch (Exception e) {
                         e.printStackTrace();
               return this;
          protected void setValue(Object value) {
               setText((value == null) ? "" : value.toString());
     public static void main(String[] args) {
          TableCellRendererBug frame = new TableCellRendererBug();
          frame.pack();
          frame.setVisible(true);
Srikanth

Similar Messages

  • Search text in sql server 2000

    how can i preapre a script to search all stored procedure, view, etc. which contain search text. just list out all the sp name, view name.

    select distinct
    object_name([id]) as obj_name,
    case
    when objectproperty([id], 'IsProcedure') = 1 then 'stored procedure'
    when objectproperty([id], 'IsScalarFunction') = 1 then 'scalar function'
    when objectproperty([id], 'IsTableFunction') = 1 then 'table function'
    when objectproperty([id], 'IsView') = 1 then 'view'
    end as obj_type
    from
    syscomments
    where
    objectproperty([id], 'IsProcedure') = 1
    or objectproperty([id], 'IsScalarFunction') = 1
    or objectproperty([id], 'IsTableFunction') = 1
    or objectproperty([id], 'IsView') = 1
    and objectproperty([id], 'IsMSShipped') = 0
    and [text] like '%orderid%'
    order by
    obj_type, obj_name
    go
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • How search text in current frame of external swf?

    Hello Everyone
    I am loading an external swf using loader.
    How do search and highlight the text in the current frame only?
    Is there a frame class which I could use?
    Thanks

    This is not likely to be possible in the general case, depending on what you mean by "searching text"
    For instance, a Word doc might have the text "Hello, world!" when viewed in Word, but that doesn't mean that the sequence of characters 'H', 'e', 'l', 'l', 'o', etc., exists in the file. There might be one letter, then some binary data indicating that the next letter is some other font or color, then one more letter, then more binary data, etc.
    Conversely, there could be textual metadata in a "binary" file that a person reading the file in the appropriate viewer would never see. Unless you know the details of the format you're reading, you won't be able to distinguish that from "real text".
    And what do you mean "strings" is not efficient? Have you tried it? Does it do what you want? Did you measure and determine that it does not meet your well-defined performance requirements? It's unlikely you'll be able to write code that does the same thing as "strings" but more "efficiently."
    The first step is to put more realistic boundaries on your requirements and define them more precisely. "Extract text from any binary file," is not a valid, meaningful, or reasonable requirement.
    EDIT: I may have misunderstood your requirements. I thought you wanted to "extract all text" from binary files. If that's not what you meant, and you're looking more to replicate grep, then follow Joachim's advice.
    Edited by: jverd on Mar 29, 2010 1:33 PM

  • How to select and search text in this document?

    http://www.oracle.com/technology/products/manageability/database/pdf/ow05/PS_S003_274003_1 06-1_FIN_v2.pdf
    is a document I can read but cannot copy text from. I can't search for any text in it either. Is there a way to convert it to a PDF file I can select and search text in? What did the author do to make it "encrypted"? Thanks.
    Yong Huang

    I notice Google can convert it to plain text:
    http://74.125.95.132/search?q=cache:e4rkLs8pPekJ:www.oracle.com/technology/products/manage ability/database/pdf/ow05/PS_S003_274003_106-1_FIN_v2.pdf+understanding+shared+pool&cd=1&h l=en&ct=clnk&gl=us
    (If that long URL doesn't work, just search for "understanding shared pool" and click "View as HTML".)
    For now I'll use that. Thanks everyone.
    Also, my local desktop search program Copernic can also index keywords in the article.

  • Find caret position of search text in jEditorPane

    Hi All,
    I am looking for a way to find the Caret position in a jeditor pane for the search text that i supply. The Jeditor pain is setup for text/html and when i find the index of my search text "ANCHOR_d" in the jeditor pane is 27000 something but the caret position is 7495 how do you find the caret position of the search text ??
    Any help is appriciated.
    I am also looking into getting abnchoring to work in the jeditorpane html text but as of yet i have been unsuccessful.
    Kind Regards,
    Wurns

    Search the underlying document, not the editor pane. Play around with this example, which I threw together the other day for a somewhat similar problem with JTextPane involving newlines, and modified for your need.
    Note: Please do not program by exception.import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.swing.JButton;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.text.Document;
    public class SearchEditorPane {
       JFrame frame = new JFrame ("Search JTextPane Test");
       String html = "<HTML><BODY><P>This is <B>some</B>" +
                    " <I>formatted</I>" +
                    " <FONT color=#ff0000>colored</FONT>" +
                    " html.</P>" +
                    "<P>This is a <FONT face=Comic Sans MS>" +
                    "comic <br>\n<br>\nsans ms</FONT> section</P><div>" +
                    "And this is a new division</div>" +
                    "</BODY></HTML>";
       JEditorPane editorPane = new JEditorPane ("text/html", html);
       JPanel panel = new JPanel ();
       JTextField textField = new JTextField (10);
       JButton button = new JButton ("Find");
       Document doc = editorPane.getDocument ();
       void makeUI () {
          editorPane.setText ("<HTML><BODY><P>This is <B>some</B>" +
                " <I>formatted</I>" +
                " <FONT color=#ff0000>colored</FONT>" +
                " html.</P>" +
                "<P>This is a <FONT face=Comic Sans MS>" +
                "comic <br>\n<br>\nsans ms</FONT> section</P><div>" +
                "And this is a new division</div>" +
                "</BODY></HTML>");
          button.addActionListener (new ActionListener () {
             public void actionPerformed (ActionEvent e) {
                // Programming by exception is BAD, don't copy this style
                // This is just to illustrate the solution to the problem at hand
                // (Sorry, uncle-alice, haven't reworked it yet)
                try {
                   Matcher matcher = Pattern.compile (textField.getText ())
                   .matcher (doc.getText (0, doc.getLength ()));
                   matcher.find ();
                   editorPane.setCaretPosition (matcher.start ());
                   editorPane.moveCaretPosition (matcher.end ());
                   editorPane.requestFocus ();
                } catch (Exception ex) {
                   JOptionPane.showMessageDialog (frame, "Not Found!\n" + ex.toString ());
                   //ex.printStackTrace();
          panel.add (textField);
          panel.add (button);
          panel.setPreferredSize (new Dimension (300, 40));
          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
          frame.setSize (300, 300);
          frame.add (editorPane, BorderLayout.CENTER);
          frame.add (panel, BorderLayout.SOUTH);
          frame.setLocationRelativeTo (null);
          frame.setVisible (true);
       public static void main (String[] args) {
          SwingUtilities.invokeLater (new Runnable () {
             public void run () {
                new SearchEditorPane ().makeUI ();
    }db

  • Search text in PDF and MS Word document

    Can any body tell me how search text in PDF and MS Word document through Java code, any body has code or any suggestion to give
    Thank You
    Adnan

    Can any body tell me how search text in PDF
    and MS Word document through Java code, any
    body has code or any suggestion to giveYes.
    First, you need to work out how to read each document type from Java.
    E.g, for MS Word you could use Apache Jakarta POI - HWPF: http://jakarta.apache.org/poi/hwpf/index.html
    Then, you use Apache Lucene to index and search.
    See http://lucene.apache.org/java/docs/index.html
    ~D

  • How to change the width of textbox in Search Texts iview

    Hi, Experts,
         I creat a search texts iview with stardard configuration to search the data in the repository.
    The problem is that the width of textbox is too short. And the user will input more than 40 characters in the textbox.
       In this way, the users can't see all the information unless he put the mouse pointer in the textbox and drag it.
       Is there any stardard configuration in MDM or MDM Portal to increase the width of textbox?
      Regards,
      Youli

    Hi Youli,
    I tried this but seems like there is no property available to change this setting. As these iViews are standard shipped, we cannot modify the design or code.
    Regards,
    Jitesh Talreja

  • Can't include a reset button/process that cleans a search text field

    Hi all
    Using apex 3.0.1 on a XE edition
    In my app there's a report that displays a lot of records.
    I included an text field item, where user can type a search criteria, then i added a button called "search" which, when submitted, display the records where search criteria is included.
    Now, my problem is that i can't put a "reset" button, which, when submmitted, is supposed to clear the search text field, so the report display all records.
    I tried adding a branch that triggers when reset buttos is pressed, clearing cache of search text field. It didn't worked, search string keeps on showing on text field.
    Then i changed the process, instead of clearing cache, setting search text field item with a value of null. Didnt work either...
    Does anyone have a good example of thjis type of reset button???
    tnks in advance....
    Fernando

    yes Earl, i know it's pretty standard...but i got some trouble... anyway, i think it was just a "lapsus brutus" o' mine... It's solved now and here's what i did:
    I created a text field button (where search string will be typed), a "submit as Go" button, and a "submit as reset" button. Then i created an uncondicional branch to same page, then i created a Clear Cache for Item process, where the text field cache is cleared, conditioned when "submit as reset" button is pressed.
    That solved the problem, thnx very much for your help
    fernando

  • Searching text in PDF

    I believe that I have heard that in GW 8 it will be possible to search text in PDF documents.
    I have tried it, but it doesn't work.
    Is there a way to make it work in GW 8?
    Thanks,
    Tomislav

    Dave Parkes wrote:
    > I don't know enough about the Linux setup to know precisely what is called
    > on that OS.
    It's still called the document conversation agent on Linux. I would set off
    an indexing run to see if it kicks it all off properly. My PDFs have been
    indexing here for a good long time :)
    Danita
    Time to upgrade to GW8!
    http://www.caledonia.net/gw8upg.html

  • Using Underscore In OIDDAS Group Search Text Box

    Hi Everyone,
    I am using the 'Directory' tab within the Oracle Self Service Console to search for user Groups.
    Most of my groups are of the form : PORT_xx_xxxx
    I am trying to search for all groups beginning PORT_ but if I enter that as a search query the underscore is treated as a single character wildcard. In my case this means the search results display PORT_xx_xxxx groups as well as a load of PORTAL_xxxx groups
    Is there a way to escape the underscore so that it is treated as a character and not a wildcard?
    If this was SQL then there is plenty of info out there about escaping underscores but nothing in relation to normal search text boxes.
    Matt

    Hi Luis,
    I tried PORT\_ but it still returns PORT_xx and PORTAL_xx results.
    I've got a feeling the text box filters out the usual escape characters making escaping the underscore impossible. It a bit annoying because it isn't as if the underscore is an unusual character to have in a group name!
    Matt

  • MDM search text iView --when searchnode it should displayall parents&childs

    Hi all
    I have create one page & added three iViews to that page. one is MDM search text iView second is resultset iView & third is Itemdetails iView.
    actually my requirement is when i search for any node in the search text iView then it has to display all the parents & child nodes of that search node. for example when i search for node india it has to all parent & all child nodes of the node "India".
    now i am able to get all the parent nodes of node "India" in the resultset iView but i am not getting the child nodes of india like karnataka,tamilnadu etc.
    now i want to display all the parents & all child nodes of the search node "India".
    Please help me on this ASAP.
    Regards
    Sunil

    Hi Sunil,
    This is the default behaviour which cant be changed. I tried this thing and I observed that if child node contains the search pattern then only it will display the entire path from root node till the child that contains the search text because it starts traversing from the top and moves till the leaf.
    If your tree is some what looks like this then only it is possible to achieve the expected behaviour.
    India
       Tamilnadu:India
       Chennai:India
    But I can understand this is not feasible. Lets wait for some replies regarding this.
    Regards,
    Jitesh Talreja

  • Centering text in JTable cells

    How do I center the text in JTable cells? By default, all data is left aligned.
    Thanks,
    Jason

    Read up on cell renderers from the Swing tutorial on "Using Tables":
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender
    Here's an example to get you started.
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    public class TableRenderer extends JFrame
        public TableRenderer()
            String[] columnNames = {"Date", "String", "Integer", "Decimal", "Boolean"};
            Object[][] data =
                {new Date(), "A", new Integer(1), new Double(5.1), new Boolean(true)},
                {new Date(), "B", new Integer(2), new Double(6.2), new Boolean(false)},
                {new Date(), "C", new Integer(3), new Double(7.3), new Boolean(true)},
                {new Date(), "D", new Integer(4), new Double(8.4), new Boolean(false)}
            DefaultTableModel model = new DefaultTableModel(data, columnNames);
            JTable table = new JTable( model )
                //  Returning the Class of each column will allow different
                //  renderers to be used based on Class
                public Class getColumnClass(int column)
                    return getValueAt(0, column).getClass();
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
            //  Create cell renderer
            TableCellRenderer centerRenderer = new CenterRenderer();
            //  Use renderer on a specific column
            TableColumn column = table.getColumnModel().getColumn(3);
            column.setCellRenderer( centerRenderer );
            //  Use renderer on a specific Class
            table.setDefaultRenderer(String.class, centerRenderer);
        public static void main(String[] args)
            TableRenderer frame = new TableRenderer();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
        **  Center the text
        class CenterRenderer extends DefaultTableCellRenderer
            public CenterRenderer()
                setHorizontalAlignment( CENTER );
            public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                return this;

  • Search text files in a folder

    Im given a project to implement a text file search engine to search text files in a folder to find matches for a given text and display the path of containing files. Here have to implement all the data structures i use.In order to search matches for given text , first i have to separate txt files and subfolders in a given folder. But i cant think of a way to separate them. does anybody have a solution?
    Thanx!

    Can you try something like this? This lists all the directories and their sub-directories along with the files. Displays the files with paths too.
    public class FileSearch {
         private static final String PATH = "C:\\temp";
              public static void main(String[] args){
                   File file = null;
                   String[] contents = null;               
                   file = new File(PATH);
                   contents = file.list();
                   for(String fileDir : contents){
                        file = new File(PATH+"\\"+fileDir);
                        if(file.isDirectory()){
                             System.out.println("["+file+"]");
                             listDirectory(file);
                        else{
                             System.out.println("     "+file);
              public static void listDirectory(File theFile){
                   String[] dirContents = null;
                   String path = theFile.getAbsolutePath();
                   if(theFile.isDirectory()){
                        dirContents = theFile.list();
                        for(String newFile : dirContents){
                             File dirFile = null;
                             dirFile = new File(path+"\\"+newFile);
                             if(dirFile.isDirectory()){
                                  System.out.println("["+dirFile+"]");
                                  listDirectory(dirFile.getAbsoluteFile());
                             else{
                                  System.out.println("     "+dirFile);
                   else{
                        System.out.println("     "+theFile);
         }

  • Trex is not searching texts in any document types other then PDF.

    Dear All
    We are implementing DMS in ECC 6.0.We have configured Trex 7.0 text search in ABAP stack. Trex not searching text in .dwg (Autocad) *.doc (Word files) files in SAP System through CV04N T-code it is not searching.
    It is searching only pdf files.
    System Details:
    Server ECC 6.0
    SAP_BASIS - SAPKB70010
    SAP_ABA - SAPKA70010
    SAP_APPL - SAPKH60007
    EA-APPL - SAPKGPAD07
    Error Message:
    We have added the mime types for full text search in SAP System, SPRO &#61664; Cross-Application Components &#61664; Document Management &#61664; General Data &#61664; Settings for Storage Systems &#61664; Maintain Storage System as application/acad & application/doc. And also in Trex server usr\sap\<SID>\TRX00\Trex\TREXValidMimeTypes.ini file.
    After adding we have restarted the Trex server & done the Reindexing in SAP System & tried. But it is not searching the text in autocad files.
    Kindly support for us, to solve this issue.
    Regards
    Harshavardhan.G
    Mob: - 91 99130 88039

    Hi Harshavardhan,
    could you please create a OSS ticket for BC-TRX and attach an example of DWG document to this. Please also check if the includehidden parameter (TREXFilter.ini) is set to true.
    Best regards,
    Mikhail

  • Validate user-entered text in JTable

    How do I validate user entered text in JTable cell, so only the values 1234567890. are acceptet? The cell should contain only doubles....

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class aslan extends JFrame {
      public aslan() {
        TableModel model = new CustomTableModel();
        JTable table = new JTable(model);
        getContentPane().add(new JScrollPane(table), "Center");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(300,200);
        setLocation(300,300);
        setVisible(true);
      private class CustomTableModel extends AbstractTableModel {
        String[] headings = new String[] {
          "Cost", "Item", "Type"
        Object[][] data = new Object[][] {
          { new Double(12.75), "glue",   "tube" },
          { new Double(15.20), "hammer", "claw" },
          { new Double(8.32),  "saw",    "hack" }
        public int getRowCount() {
          return data.length;
        public int getColumnCount() {
          return data[0].length;
        public Object getValueAt(int row, int column) {
          return data[row][column];
        public void setValueAt(Object value, int row, int column) {
          data[row][column] = value;
          fireTableDataChanged();
        public String getColumnName(int column) {
          return headings[column];
        public Class getColumnClass(int column) {
          return data[0][column].getClass();
        public boolean isCellEditable(int row, int column) {
          return true;
      public static void main(String[] args) {
        new aslan();
    }

Maybe you are looking for