Link to home
Start Free TrialLog in
Avatar of mpriyatam
mpriyatam

asked on

Line Highlighting in a JTextPane/JEditorPane with a text file as an input

Just as in any Java IDE (JBuilder, eclipse) when you compile a  class, you get errors listed below in a table format; when you click one of the rows in the table, the error is highlighted in the above editor in the corresponding line.

I have a similar requirement.

I have created a tableModel for errors & I can capture the line no in the text file (although the line no is not explicitly mentioned in the text file). I just need a very basic editor (very very basic) which shows cobol code in it & when onClick on the table, should traverse to the exact line no highlighting the entire LINE.

1) how to interpret lines in a TextPane/EditorPane & sucessfully jump to line nos?
(Im dealing with 100's of lines of text file, so loading into a string array oR JList will reduce the perf)
2)how to highlight the entire line, once i know the line no?

Can anybody suggest how to go about this??

So far, Ive tried adding CaretListener's but it aint working.
Avatar of expertmb
expertmb

this code might help you

import javax.swing.JTextPane;
import javax.swing.JFrame;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyleConstants;
import javax.swing.text.MutableAttributeSet;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowAdapter;

import java.awt.Color;
import java.awt.Font;
import java.awt.BorderLayout;

public class TextPaneExample extends WindowAdapter {

    public TextPaneExample() {
        JFrame f = new JFrame("Second JTextPane Example");
        f.getContentPane().setLayout(new BorderLayout());


        JTextPane text = new JTextPane();
        Font font = new Font("Serif", Font.ITALIC, 20);
        MutableAttributeSet attrs = text.getInputAttributes();
        StyledDocument doc = text.getStyledDocument();
        StyleConstants.setForeground(attrs, Color.yellow);
            StyleConstants.setBackground(attrs, Color.red);
        doc.setCharacterAttributes(10, doc.getLength() + 1, attrs, false);

        f.getContentPane().add(text, BorderLayout.CENTER);

        // Listen for the user to click the frame's close box
        f.addWindowListener(this);
        f.setSize(400, 400);
        f.show();
    }


    public void windowClosing(WindowEvent evt) {
        System.exit(0);
    }

    public static void main(String[] args) {
        TextPaneExample3 instance = new TextPaneExample3();
    }

}

Avatar of mpriyatam

ASKER

there were 2 answers to my question ... & i think even after combining both of them, im not getting it!!
The code u provided, will highlight the input chars. ok., let me be more precise.

1) load a text file to textPane
2) while loading, the line nos should be automatically prefixed for the file
3) given a line no., goto a line no # & highlight the entire line no

i tried modifying the code but still not able to get what i wanted., pl help !!
I think you should just select that line.
;JOOP!
i dont get it !!
well all im asking is the algorithm for 2 functions -
-> loadLineNumberedFile(JTextPane, File) - which will load a text file with line nos
-> highlightLine(JTextPane,int) - given a line no, goes to the line no & Highlights it
>>-> highlightLine(JTextPane,int) - given a line no, goes to the line no & Highlights it
mpriyatam,
i am working on it.
>>-> highlightLine(JTextPane,int) - given a line no, goes to the line no & Highlights it
its done here. some bugs migth be there.

it may help you.


import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;

import javax.swing.*;
import javax.swing.JTextPane;
import javax.swing.JFrame;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyleConstants;
import javax.swing.text.MutableAttributeSet;

import java.util.StringTokenizer;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowAdapter;

import java.awt.Color;
import java.awt.Font;
import java.awt.BorderLayout;

public class TextPaneExample extends WindowAdapter {
JFrame f = new JFrame("Second JTextPane Example");
    public TextPaneExample() {

        f.getContentPane().setLayout(new BorderLayout());
          JMenuBar menuBar = new JMenuBar();



        final JTextPane text = new JTextPane();
        Font font = new Font("Serif", Font.ITALIC, 20);
        MutableAttributeSet attrs = text.getInputAttributes();
        StyledDocument doc = text.getStyledDocument();
        StyleConstants.setForeground(attrs, Color.blue);
        doc.setCharacterAttributes(0, doc.getLength() + 1, attrs, false);

               init(text);

          // Create a menu
            JMenu menu = new JMenu("Goto Line No.");

            JMenuItem item = new JMenuItem("Select Line No.");
            item.addActionListener(new ActionListener(){
                  public void actionPerformed(ActionEvent e){
                        SelectLineNo lineNo = new SelectLineNo(null, true);
                        Font font = new Font("Serif", Font.ITALIC, 20);
                        MutableAttributeSet attrs = text.getInputAttributes();
                        StyledDocument doc = text.getStyledDocument();
                        StyleConstants.setForeground(attrs, Color.yellow);
                        StyleConstants.setBackground(attrs, Color.red);

                        String str = text.getText();

                        int tokens = 0;
                        StringTokenizer tokenizer = new StringTokenizer(str,new String("\n"));
                    tokens = tokenizer.countTokens();

                        int count = 0;
                        int count1 = 0;
                        int line = lineNo.getLineNumber();

                        System.out.println("line: " + line);
                        int lineCount = 0;
                        for(;tokenizer.hasMoreTokens();){
                              if(lineCount < line)
                                    count += tokenizer.nextToken().length();
                              else if(lineCount == line){
                                    count1 = count + tokenizer.nextToken().length();
                                    break;
                              }
                              lineCount++;
                        }

                        doc.setCharacterAttributes(count, count1, attrs, false);

                        StyleConstants.setForeground(attrs, Color.blue);
                        StyleConstants.setBackground(attrs, Color.white);
                        doc.setCharacterAttributes(0, count, attrs, false);
                        doc.setCharacterAttributes(count1, doc.getLength(), attrs, false);
                  }
            });
            menu.add(item);

            menuBar.add(menu);


         f.setJMenuBar(menuBar);
         f.getContentPane().add(text, BorderLayout.CENTER);

        // Listen for the user to click the frame's close box
        f.addWindowListener(this);
        f.setSize(400, 400);
        f.show();
    }

      private void init(final JTextPane text){

            final JPopupMenu menu = new JPopupMenu();

                // Create and add a menu item
                JMenuItem item = new JMenuItem("Select Line No.");
                item.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent e){

                        SelectLineNo lineNo = new SelectLineNo(null, true);


                        Font font = new Font("Serif", Font.ITALIC, 20);
                        MutableAttributeSet attrs = text.getInputAttributes();
                        StyledDocument doc = text.getStyledDocument();
                        StyleConstants.setForeground(attrs, Color.yellow);
                        StyleConstants.setBackground(attrs, Color.red);

                        String str = text.getText();

                        int tokens = 0;
                        StringTokenizer tokenizer = new StringTokenizer(str,new String("\n"));
                    tokens = tokenizer.countTokens();

                        int count = 0;
                        int count1 = 0;
                        int line = lineNo.getLineNumber();

                        System.out.println("line: " + line);
                        int lineCount = 0;
                        for(;tokenizer.hasMoreTokens();){
                              if(lineCount < line)
                                    count += tokenizer.nextToken().length();
                              else if(lineCount == line){
                                    count1 = count + tokenizer.nextToken().length();
                                    break;
                              }
                              lineCount++;
                        }

                        doc.setCharacterAttributes(count, count1, attrs, false);

                        StyleConstants.setForeground(attrs, Color.blue);
                        StyleConstants.setBackground(attrs, Color.white);
                        doc.setCharacterAttributes(0, count, attrs, false);
                        doc.setCharacterAttributes(count1, doc.getLength(), attrs, false);
                        }
                  });
                menu.add(item);

                // Set the component to show the popup menu
                text.addMouseListener(new MouseAdapter() {
                    public void mousePressed(MouseEvent evt) {
                        if (evt.isPopupTrigger()) {
                            menu.show(evt.getComponent(), evt.getX(), evt.getY());
                        }
                    }
                    public void mouseReleased(MouseEvent evt) {
                        if (evt.isPopupTrigger()) {
                            menu.show(evt.getComponent(), evt.getX(), evt.getY());
                        }
                    }
                });
      }
    public void windowClosing(WindowEvent evt) {
        System.exit(0);
    }

    public static void main(String[] args) {
        TextPaneExample instance = new TextPaneExample();
    }

}


class SelectLineNo extends JDialog implements ActionListener{

      JTextField txtField = new JTextField();
      JButton btnOk = new JButton("Ok");
      int lineNumber = 0;

      public SelectLineNo(Dialog dlg, boolean modal){
            btnOk.setName("Ok");
            this.getContentPane().add(txtField, BorderLayout.CENTER);
            this.getContentPane().add(btnOk, BorderLayout.SOUTH);
            btnOk.addActionListener(this);
            this.setTitle("Select Line no.");
            this.setSize(200, 100);
            this.setModal(modal);
        this.show();
      }

      public void actionPerformed(ActionEvent event){
            Object obj = event.getSource();

            if(obj instanceof JButton){
                  if(((JButton)obj).getName().equalsIgnoreCase("Ok")){
                        String str = txtField.getText();

                        if(str != null && ! str.equals("")){
                              try{
                                    lineNumber = Integer.parseInt(str);
                              }catch(Exception ex){
                                    lineNumber = 0;
                              }
                        }
                        this.setVisible(false);
                  }
            }
      }

      int  getLineNumber(){
            return lineNumber;
      }
}

fantastic!! the jumping/ highlighting works. Let me see if I can combine your code with the code here
http://www.developer.com/java/other/article.php/3318421

which automatically generates ... line nos.

I just want the file to be loaded with file nos generated  

thanks a ton !!! I will try & get back to you .. in case you have the complete solution please do try !
here is the modified source


import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

import java.util.StringTokenizer;

import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;


class LNTextPane1 extends JFrame {
    public LNTextPane1() {
        JEditorPane edit = new JEditorPane();
        edit.setEditorKit(new NumberedEditorKit());

            init(edit);
        JScrollPane scroll = new JScrollPane(edit);
        getContentPane().add(scroll);
        setSize(300, 300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }


          private void init(final JEditorPane edit){

                  final JPopupMenu menu = new JPopupMenu();

                      // Create and add a menu item
                      JMenuItem item = new JMenuItem("Select Line No.");
                      item.addActionListener(new ActionListener(){
                              public void actionPerformed(ActionEvent e){

                              SelectLineNo lineNo = new SelectLineNo(null, true);

                              String str = edit.getText();

                              int tokens = 0;
                              StringTokenizer tokenizer = new StringTokenizer(str,new String("\n"));
                          tokens = tokenizer.countTokens();

                              int count = 0;
                              int count1 = 0;
                              int line = lineNo.getLineNumber() - 1;
                              int lineCount = 0;

                              if(line >= 0){
                                    for(;tokenizer.hasMoreTokens();){
                                          if(lineCount < line)
                                                count += tokenizer.nextToken().length();
                                          else if(lineCount == line){
                                                count1 = count + tokenizer.nextToken().length();
                                                break;
                                          }
                                          lineCount++;
                                    }
                              }
                              edit.setSelectionStart(count);
                              edit.setSelectionEnd(count1);
                              edit.setSelectedTextColor(Color.yellow);
                              edit.setSelectionColor(Color.blue);
                              }
                        });
                      menu.add(item);

                      // Set the component to show the popup menu
                      edit.addMouseListener(new MouseAdapter() {
                          public void mousePressed(MouseEvent evt) {
                              if (evt.isPopupTrigger()) {
                                  menu.show(evt.getComponent(), evt.getX(), evt.getY());
                              }
                          }
                          public void mouseReleased(MouseEvent evt) {
                              if (evt.isPopupTrigger()) {
                                  menu.show(evt.getComponent(), evt.getX(), evt.getY());
                              }
                          }
                      });
      }

    public static void main(String a[]) {
        new LNTextPane1();
    }
}

class NumberedEditorKit extends StyledEditorKit {
    public ViewFactory getViewFactory() {
        return new NumberedViewFactory();
    }
}

class NumberedViewFactory implements ViewFactory {
    public View create(Element elem) {
        String kind = elem.getName();

        if (kind != null)
            if (kind.equals(AbstractDocument.ContentElementName)) {
                return new LabelView(elem);
            }
            else if (kind.equals(AbstractDocument.
                             ParagraphElementName)) {
//              return new ParagraphView(elem);
                return new NumberedParagraphView(elem);
            }
            else if (kind.equals(AbstractDocument.
                     SectionElementName)) {
                return new BoxView(elem, View.Y_AXIS);
            }
            else if (kind.equals(StyleConstants.
                     ComponentElementName)) {
                return new ComponentView(elem);
            }
            else if (kind.equals(StyleConstants.IconElementName)) {
                return new IconView(elem);
            }
        // default to text display
        return new LabelView(elem);
    }
}

class NumberedParagraphView extends ParagraphView {
    public static short NUMBERS_WIDTH=25;

    public NumberedParagraphView(Element e) {
        super(e);
        short top = 0;
        short left = 0;
        short bottom = 0;
        short right = 0;
        this.setInsets(top, left, bottom, right);
    }

    protected void setInsets(short top, short left, short bottom,
                             short right) {super.setInsets
                             (top,(short)(left+NUMBERS_WIDTH),
                             bottom,right);
    }

    public void paintChild(Graphics g, Rectangle r, int n) {
        super.paintChild(g, r, n);
        int previousLineCount = getPreviousLineCount();
        int numberX = r.x - getLeftInset();
        int numberY = r.y + r.height - 5;
        g.drawString(Integer.toString(previousLineCount + n + 1),
                                      numberX, numberY);
    }

    public int getPreviousLineCount() {
        int lineCount = 0;
        View parent = this.getParent();
        int count = parent.getViewCount();
        for (int i = 0; i < count; i++) {
            if (parent.getView(i) == this) {
                break;
            }
            else {
                lineCount += parent.getView(i).getViewCount();
            }
        }
        return lineCount;
    }
}

class SelectLineNo extends JDialog implements ActionListener{

      JTextField txtField = new JTextField();
      JButton btnOk = new JButton("Ok");
      int lineNumber = 0;

      public SelectLineNo(Dialog dlg, boolean modal){
            btnOk.setName("Ok");
            this.getContentPane().add(txtField, BorderLayout.CENTER);
            this.getContentPane().add(btnOk, BorderLayout.SOUTH);
            btnOk.addActionListener(this);
            this.setTitle("Select Line no.");
            this.setSize(200, 100);
            this.setModal(modal);
        this.show();
      }

      public void actionPerformed(ActionEvent event){
            Object obj = event.getSource();

            if(obj instanceof JButton){
                  if(((JButton)obj).getName().equalsIgnoreCase("Ok")){
                        String str = txtField.getText();

                        if(str != null && ! str.equals("")){
                              try{
                                    lineNumber = Integer.parseInt(str);
                              }catch(Exception ex){
                                    lineNumber = 0;
                              }
                        }
                        this.setVisible(false);
                  }
            }
      }

      int  getLineNumber(){
            return lineNumber;
      }
}
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

import java.util.StringTokenizer;

import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;


class LNTextPane1 extends JFrame {

    public LNTextPane1() {
        final JEditorPane edit = new JEditorPane();
        edit.setEditorKit(new NumberedEditorKit());

            JMenuBar menuBar = new JMenuBar();

          // Create a menu
            JMenu menu = new JMenu("Goto Line No.");

            JMenuItem item = new JMenuItem("Select Line No.");
            item.addActionListener(new ActionListener(){
                  public void actionPerformed(ActionEvent e){
                              SelectLineNo lineNo = new SelectLineNo(null, true);

                              String str = edit.getText();

                              int tokens = 0;
                              StringTokenizer tokenizer = new StringTokenizer(str,new String("\n"));
                          tokens = tokenizer.countTokens();

                              int count = 0;
                              int count1 = 0;
                              int line = lineNo.getLineNumber() - 1;
                              int lineCount = 0;

                              if(line >= 0){
                                    for(;tokenizer.hasMoreTokens();){
                                          if(lineCount < line)
                                                count += tokenizer.nextToken().length();
                                          else if(lineCount == line){
                                                count1 = count + tokenizer.nextToken().length();
                                                break;
                                          }
                                          lineCount++;
                                    }
                              }
                              edit.setSelectionStart(count);
                              edit.setSelectionEnd(count1);
                              edit.setSelectedTextColor(Color.yellow);
                              edit.setSelectionColor(Color.blue);
                  }
            });
            menu.add(item);
            menuBar.add(menu);
          this.setJMenuBar(menuBar);

            init(edit);

        JScrollPane scroll = new JScrollPane(edit);
        getContentPane().add(scroll);
        setSize(300, 300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }


          private void init(final JEditorPane edit){

                  final JPopupMenu menu = new JPopupMenu();

                      // Create and add a menu item
                      JMenuItem item = new JMenuItem("Select Line No.");
                      item.addActionListener(new ActionListener(){
                              public void actionPerformed(ActionEvent e){

                              SelectLineNo lineNo = new SelectLineNo(null, true);

                              String str = edit.getText();

                              int tokens = 0;
                              StringTokenizer tokenizer = new StringTokenizer(str,new String("\n"));
                          tokens = tokenizer.countTokens();

                              int count = 0;
                              int count1 = 0;
                              int line = lineNo.getLineNumber() - 1;
                              int lineCount = 0;

                              if(line >= 0){
                                    for(;tokenizer.hasMoreTokens();){
                                          if(lineCount < line)
                                                count += tokenizer.nextToken().length();
                                          else if(lineCount == line){
                                                count1 = count + tokenizer.nextToken().length();
                                                break;
                                          }
                                          lineCount++;
                                    }
                              }
                              edit.setSelectionStart(count);
                              edit.setSelectionEnd(count1);
                              edit.setSelectedTextColor(Color.yellow);
                              edit.setSelectionColor(Color.blue);
                              }
                        });
                      menu.add(item);

                      // Set the component to show the popup menu
                      edit.addMouseListener(new MouseAdapter() {
                          public void mousePressed(MouseEvent evt) {
                              if (evt.isPopupTrigger()) {
                                  menu.show(evt.getComponent(), evt.getX(), evt.getY());
                              }
                          }
                          public void mouseReleased(MouseEvent evt) {
                              if (evt.isPopupTrigger()) {
                                  menu.show(evt.getComponent(), evt.getX(), evt.getY());
                              }
                          }
                      });
      }

    public static void main(String a[]) {
        new LNTextPane1();
    }
}

class NumberedEditorKit extends StyledEditorKit {
    public ViewFactory getViewFactory() {
        return new NumberedViewFactory();
    }
}

class NumberedViewFactory implements ViewFactory {
    public View create(Element elem) {
        String kind = elem.getName();

        if (kind != null)
            if (kind.equals(AbstractDocument.ContentElementName)) {
                return new LabelView(elem);
            }
            else if (kind.equals(AbstractDocument.
                             ParagraphElementName)) {
//              return new ParagraphView(elem);
                return new NumberedParagraphView(elem);
            }
            else if (kind.equals(AbstractDocument.
                     SectionElementName)) {
                return new BoxView(elem, View.Y_AXIS);
            }
            else if (kind.equals(StyleConstants.
                     ComponentElementName)) {
                return new ComponentView(elem);
            }
            else if (kind.equals(StyleConstants.IconElementName)) {
                return new IconView(elem);
            }
        // default to text display
        return new LabelView(elem);
    }
}

class NumberedParagraphView extends ParagraphView {
    public static short NUMBERS_WIDTH=25;

    public NumberedParagraphView(Element e) {
        super(e);
        short top = 0;
        short left = 0;
        short bottom = 0;
        short right = 0;
        this.setInsets(top, left, bottom, right);
    }

    protected void setInsets(short top, short left, short bottom,
                             short right) {super.setInsets
                             (top,(short)(left+NUMBERS_WIDTH),
                             bottom,right);
    }

    public void paintChild(Graphics g, Rectangle r, int n) {
        super.paintChild(g, r, n);
        int previousLineCount = getPreviousLineCount();
        int numberX = r.x - getLeftInset();
        int numberY = r.y + r.height - 5;
        g.drawString(Integer.toString(previousLineCount + n + 1),
                                      numberX, numberY);
    }

    public int getPreviousLineCount() {
        int lineCount = 0;
        View parent = this.getParent();
        int count = parent.getViewCount();
        for (int i = 0; i < count; i++) {
            if (parent.getView(i) == this) {
                break;
            }
            else {
                lineCount += parent.getView(i).getViewCount();
            }
        }
        return lineCount;
    }
}

class SelectLineNo extends JDialog implements ActionListener{

      JTextField txtField = new JTextField();
      JButton btnOk = new JButton("Ok");
      int lineNumber = 0;

      public SelectLineNo(Dialog dlg, boolean modal){
            btnOk.setName("Ok");
            this.getContentPane().add(txtField, BorderLayout.CENTER);
            this.getContentPane().add(btnOk, BorderLayout.SOUTH);
            btnOk.addActionListener(this);
            this.setTitle("Select Line no.");
            this.setSize(200, 100);
            this.setModal(modal);
        this.show();
      }

      public void actionPerformed(ActionEvent event){
            Object obj = event.getSource();

            if(obj instanceof JButton){
                  if(((JButton)obj).getName().equalsIgnoreCase("Ok")){
                        String str = txtField.getText();

                        if(str != null && ! str.equals("")){
                              try{
                                    lineNumber = Integer.parseInt(str);
                              }catch(Exception ex){
                                    lineNumber = 0;
                              }
                        }
                        this.setVisible(false);
                  }
            }
      }

      int  getLineNumber(){
            return lineNumber;
      }
}
hey, its not generating line nos although youve copied the same code for NumberedEditorKit
Also you havent come out with the - loadFile(TextPane, File) method which was the main object of this post

PLEASE .. if poss try, Im sure you can

thanks !!!!
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

import java.util.StringTokenizer;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;


class LNTextPane1 extends JFrame {

    public LNTextPane1() {
        final JEditorPane edit = new JEditorPane();
        edit.setEditorKit(new NumberedEditorKit());

            readFile("d:\\RND\\hello.txt", edit);

            JMenuBar menuBar = new JMenuBar();

          // Create a menu
            JMenu menu = new JMenu("Goto Line No.");

            JMenuItem item = new JMenuItem("Select Line No.");
            item.addActionListener(new ActionListener(){
                  public void actionPerformed(ActionEvent e){
                              SelectLineNo lineNo = new SelectLineNo(null, true);

                              String str = edit.getText();

                              int tokens = 0;
                              StringTokenizer tokenizer = new StringTokenizer(str,new String("\n"));
                          tokens = tokenizer.countTokens();

                              int count = 0;
                              int count1 = 0;
                              int line = lineNo.getLineNumber() - 1;
                              int lineCount = 0;

                              if(line >= 0){
                                    for(;tokenizer.hasMoreTokens();){
                                          if(lineCount < line)
                                                count += tokenizer.nextToken().length();
                                          else if(lineCount == line){
                                                count1 = count + tokenizer.nextToken().length();
                                                break;
                                          }
                                          lineCount++;
                                    }
                              }
                              edit.setSelectionStart(count);
                              edit.setSelectionEnd(count1);
                              edit.setSelectedTextColor(Color.yellow);
                              edit.setSelectionColor(Color.blue);
                  }
            });
            menu.add(item);
            menuBar.add(menu);
          this.setJMenuBar(menuBar);

            init(edit);

        JScrollPane scroll = new JScrollPane(edit);
        getContentPane().add(scroll);
        setSize(300, 300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }


      void readFile(String fileName, JEditorPane edit){
            try {
                  BufferedReader stream = new BufferedReader(new InputStreamReader(new
                                                      FileInputStream(fileName)));
                  String line = null;
                  StringBuffer sb = new StringBuffer();
                  while (null != (line = stream.readLine())) {
                        sb.append(line);
                        sb.append("\n");
                        edit.setText(sb.toString());
                  }
            }catch(Exception ex){
                  ex.printStackTrace();
            }
      }
          private void init(final JEditorPane edit){

                  final JPopupMenu menu = new JPopupMenu();

                      // Create and add a menu item
                      JMenuItem item = new JMenuItem("Select Line No.");
                      item.addActionListener(new ActionListener(){
                              public void actionPerformed(ActionEvent e){

                              SelectLineNo lineNo = new SelectLineNo(null, true);

                              String str = edit.getText();

                              int tokens = 0;
                              StringTokenizer tokenizer = new StringTokenizer(str,new String("\n"));
                          tokens = tokenizer.countTokens();

                              int count = 0;
                              int count1 = 0;
                              int line = lineNo.getLineNumber() - 1;
                              int lineCount = 0;

                              if(line >= 0){
                                    for(;tokenizer.hasMoreTokens();){
                                          if(lineCount < line)
                                                count += tokenizer.nextToken().length();
                                          else if(lineCount == line){
                                                count1 = count + tokenizer.nextToken().length();
                                                break;
                                          }
                                          lineCount++;
                                    }
                              }
                              edit.setSelectionStart(count);
                              edit.setSelectionEnd(count1);
                              edit.setSelectedTextColor(Color.yellow);
                              edit.setSelectionColor(Color.blue);
                              }
                        });
                      menu.add(item);

                      // Set the component to show the popup menu
                      edit.addMouseListener(new MouseAdapter() {
                          public void mousePressed(MouseEvent evt) {
                              if (evt.isPopupTrigger()) {
                                  menu.show(evt.getComponent(), evt.getX(), evt.getY());
                              }
                          }
                          public void mouseReleased(MouseEvent evt) {
                              if (evt.isPopupTrigger()) {
                                  menu.show(evt.getComponent(), evt.getX(), evt.getY());
                              }
                          }
                      });
      }

    public static void main(String a[]) {
        new LNTextPane1();
    }
}

class NumberedEditorKit extends StyledEditorKit {
    public ViewFactory getViewFactory() {
        return new NumberedViewFactory();
    }
}

class NumberedViewFactory implements ViewFactory {
    public View create(Element elem) {
        String kind = elem.getName();

        if (kind != null)
            if (kind.equals(AbstractDocument.ContentElementName)) {
                return new LabelView(elem);
            }
            else if (kind.equals(AbstractDocument.
                             ParagraphElementName)) {
//              return new ParagraphView(elem);
                return new NumberedParagraphView(elem);
            }
            else if (kind.equals(AbstractDocument.
                     SectionElementName)) {
                return new BoxView(elem, View.Y_AXIS);
            }
            else if (kind.equals(StyleConstants.
                     ComponentElementName)) {
                return new ComponentView(elem);
            }
            else if (kind.equals(StyleConstants.IconElementName)) {
                return new IconView(elem);
            }
        // default to text display
        return new LabelView(elem);
    }
}

class NumberedParagraphView extends ParagraphView {
    public static short NUMBERS_WIDTH=25;

    public NumberedParagraphView(Element e) {
        super(e);
        short top = 0;
        short left = 0;
        short bottom = 0;
        short right = 0;
        this.setInsets(top, left, bottom, right);
    }

    protected void setInsets(short top, short left, short bottom,
                             short right) {super.setInsets
                             (top,(short)(left+NUMBERS_WIDTH),
                             bottom,right);
    }

    public void paintChild(Graphics g, Rectangle r, int n) {
        super.paintChild(g, r, n);
        int previousLineCount = getPreviousLineCount();
        int numberX = r.x - getLeftInset();
        int numberY = r.y + r.height - 5;
        g.drawString(Integer.toString(previousLineCount + n + 1),
                                      numberX, numberY);
    }

    public int getPreviousLineCount() {
        int lineCount = 0;
        View parent = this.getParent();
        int count = parent.getViewCount();
        for (int i = 0; i < count; i++) {
            if (parent.getView(i) == this) {
                break;
            }
            else {
                lineCount += parent.getView(i).getViewCount();
            }
        }
        return lineCount;
    }
}

class SelectLineNo extends JDialog implements ActionListener{

      JTextField txtField = new JTextField();
      JButton btnOk = new JButton("Ok");
      int lineNumber = 0;

      public SelectLineNo(Dialog dlg, boolean modal){
            btnOk.setName("Ok");
            this.getContentPane().add(txtField, BorderLayout.CENTER);
            this.getContentPane().add(btnOk, BorderLayout.SOUTH);
            btnOk.addActionListener(this);
            this.setTitle("Select Line no.");
            this.setSize(200, 100);
            this.setModal(modal);
        this.show();
      }

      public void actionPerformed(ActionEvent event){
            Object obj = event.getSource();

            if(obj instanceof JButton){
                  if(((JButton)obj).getName().equalsIgnoreCase("Ok")){
                        String str = txtField.getText();

                        if(str != null && ! str.equals("")){
                              try{
                                    lineNumber = Integer.parseInt(str);
                              }catch(Exception ex){
                                    lineNumber = 0;
                              }
                        }
                        this.setVisible(false);
                  }
            }
      }

      int  getLineNumber(){
            return lineNumber;
      }
}
it still doesnt work, even Ive tried the same before hence the repeated requests !!

I think the ViewFactory's create method overrides everything in the EditorKit , inspite of initialising the editor pane with a text file.

Any solutions to get over this??
you have to load the file after this call - edit.setEditorKit(new NumberedEditorKit());

& it works !!!!
do you see anyother problem with code.
wait, your code still doesnt work., im trying on a merged version of  LnTextPane wherein the above call works.
So my loadFile(textPane, file) works .. i guess if i modularise & remove your text pane it should work on my code too.

lemme confirm ...

thanks again!!
ASKER CERTIFIED SOLUTION
Avatar of expertmb
expertmb

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
working !!!!!!!!! you're a genius :)
mind giving your mail id for some personal praises !!!!

i will post the final modularised code & approve your answer!
please give your mail id.
mpriyatam@yahoo.co.in
Ok.. the final version of the supposedly 'EditorPane wiht generated Line nos with Line highlighting' is

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import java.util.StringTokenizer;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;


class LineEditor extends JEditorPane
{
          
    public LineEditor()
    {
          setEditorKit(new NumberedEditorKit());                 
    }

       public void readFile(String fileName)
       {
      try {
           BufferedReader stream = new BufferedReader
                       (new InputStreamReader(new FileInputStream(fileName)));
           String line = null;
           StringBuffer sb = new StringBuffer();
           while (null != (line = stream.readLine()))
           {
                sb.append(line);
                sb.append("\n");
                setText(sb.toString());
           }
      }catch(Exception ex)
      {
           ex.printStackTrace();
      }
       }
     
     public void gotoLine(int lne)
     {
           String str = getText();

        int tokens = 0;
        StringTokenizer tokenizer =
              new StringTokenizer(str,new String("\n"));
        tokens = tokenizer.countTokens();

        int count = 0;
        int count1 = 0;
        int line = lne - 1;
        int lineCount = 0;

        if(tokens < line)
                  setSelectedTextColor(Color.black);

        if(line >= 0)
        {
             for(;tokenizer.hasMoreTokens();)
             {
                  String str1 = tokenizer.nextToken();
                  if(lineCount < line)
                       count += str1.length();
                  else if(lineCount == line)
                  {
                       count1 = count + str1.length();
                       break;
                  }
                  lineCount++;
             }
        }

        setSelectionStart(count+line);
        setSelectionEnd(count1+line+1);    
        setSelectionColor(Color.red);              
     }      
}

class NumberedEditorKit extends StyledEditorKit {
    public ViewFactory getViewFactory() {
        return new NumberedViewFactory();
    }
}

class NumberedViewFactory implements ViewFactory {
    public View create(Element elem) {
        String kind = elem.getName();

        if (kind != null)
            if (kind.equals(AbstractDocument.ContentElementName)) {
                return new LabelView(elem);
            }
            else if (kind.equals(AbstractDocument.
                             ParagraphElementName)) {
//              return new ParagraphView(elem);
                return new NumberedParagraphView(elem);
            }
            else if (kind.equals(AbstractDocument.
                     SectionElementName)) {
                return new BoxView(elem, View.Y_AXIS);
            }
            else if (kind.equals(StyleConstants.
                     ComponentElementName)) {
                return new ComponentView(elem);
            }
            else if (kind.equals(StyleConstants.IconElementName)) {
                return new IconView(elem);
            }
        // default to text display
        return new LabelView(elem);
    }
}

class NumberedParagraphView extends ParagraphView {
    public static short NUMBERS_WIDTH=25;

    public NumberedParagraphView(Element e) {
        super(e);
        short top = 0;
        short left = 0;
        short bottom = 0;
        short right = 0;
        this.setInsets(top, left, bottom, right);
    }

    protected void setInsets(short top, short left, short bottom,
                             short right) {super.setInsets
                             (top,(short)(left+NUMBERS_WIDTH),
                             bottom,right);
    }

    public void paintChild(Graphics g, Rectangle r, int n) {
        super.paintChild(g, r, n);
        int previousLineCount = getPreviousLineCount();
        int numberX = r.x - getLeftInset();
        int numberY = r.y + r.height - 5;
        g.drawString(Integer.toString(previousLineCount + n + 1),
                                      numberX, numberY);
    }

    public int getPreviousLineCount() {
        int lineCount = 0;
        View parent = this.getParent();
        int count = parent.getViewCount();
        for (int i = 0; i < count; i++) {
            if (parent.getView(i) == this) {
                break;
            }
            else {
                lineCount += parent.getView(i).getViewCount();
            }
        }
        return lineCount;
    }
}


Usage -
call readFile(String) to load a file to the JEditorPane
call gotoLine(int) to goto a particular line in the editor.