2

My Text file contains these contents:

public class MyC{
public void MyMethod()
{
    System.out.println("My method has been accessed");
    System.out.println("hi");
}
}

I want to underline the first line public class MyC{ red when I load the text file in the JTextPane. Can someone guide me on this? I tried looking at http://docs.oracle.com/javase/7/docs/api/javax/swing/text/Highlighter.html but it is using positions. I cant figure out how to do it.

This is what I have so far:

  public class ReadDemo {

    // read the file into the pane

    static void readin(String fn, JTextComponent pane) {
        try {
            FileReader fr = new FileReader(fn);
            pane.read(fr, null);
            fr.close();
        }
        catch (IOException e) {
            System.err.println(e);
        }
    }

    public static void main(String args[]) {
        final JFrame frame = new JFrame("Testing");
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        // set up the text pane, either a JTextArea or JTextPane

        final JTextComponent textpane = new JTextArea();

        //final JTextComponent textpane = new JTextPane();

        // set up a scroll pane for the text pane

        final JScrollPane pane = new JScrollPane(textpane);
        pane.setPreferredSize(new Dimension(600, 600));


        // set up the file chooser

        String cwd = System.getProperty("user.dir");
        final JFileChooser jfc = new JFileChooser(cwd);
        final JLabel elapsed = new JLabel("Elapsed time: ");

        JButton filebutton = new JButton("Choose File");
        filebutton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (jfc.showOpenDialog(frame) !=
                    JFileChooser.APPROVE_OPTION)
                        return;
                File f = jfc.getSelectedFile();

                // record the current time and read the file

                final long s_time = System.currentTimeMillis();
                frame.setCursor(Cursor.getPredefinedCursor(
                    Cursor.WAIT_CURSOR));
                readin(f.toString(), textpane);

                // wait for read to complete and update time

                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        frame.setCursor(Cursor.
                            getPredefinedCursor(
                            Cursor.DEFAULT_CURSOR));
                        long t = System.currentTimeMillis() -
                               s_time;
                        elapsed.setText("Elapsed time: " + t);
                    }
                });
            }
        });

        JPanel buttonpanel = new JPanel();
        buttonpanel.add(filebutton);
        buttonpanel.add(elapsed);

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add("North", buttonpanel);
        panel.add("East", pane);


        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}
Afshin Moazami
  • 2,092
  • 5
  • 33
  • 55
Deathstar
  • 75
  • 5
  • 13
  • [for example](http://stackoverflow.com/a/9022901/714968) – mKorbel Jan 09 '13 at 08:20
  • Yes something like this, but how can I highlight line 1,2,3 when i load the file in the pane. – Deathstar Jan 09 '13 at 08:35
  • this is exactly in the code, a new line from File is Font changed, depends of, answer one talking about line from File, answers 2nd talkind about line from view, don't forget to up_vote (both???) correct answer and accept that, both are correct, up to you – mKorbel Jan 09 '13 at 08:38

2 Answers2

3

you can try like this:

 static void readin(String fn, JTextComponent pane) {
    try {
        FileReader fr = new FileReader(fn);
        pane.read(fr, null);
        fr.close();
        Highlighter hilit = new DefaultHighlighter();
        Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.yellow);
        pane.setHighlighter(hilit);
        hilit.addHighlight(0, pane.getText().indexOf("\n"), painter);
    }
    catch (IOException e) {
        System.err.println(e);
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
}

point is you can get index for the first line end and use it while adding highlight.

For any line/s, you can try:

 static void readin(String fn, JTextComponent pane) {
    try {
        FileReader fr = new FileReader(fn);
        pane.read(fr, null);
        fr.close();
        Highlighter hilit = new DefaultHighlighter();
        Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.yellow);
        pane.setHighlighter(hilit);
        hilit.addHighlight(getLineEndIdx(pane.getText(), 4), getLineEndIdx(pane.getText(), 8 ), painter);
    }
    catch (IOException e) {
        System.err.println(e);
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
}

private static int getLineEndIdx(String text, int lineNo) {
    int lineEndIdx = 0;
    for(int i = 1; i <= lineNo && lineEndIdx + 1 < text.length(); i++)
    {
        lineEndIdx = text.indexOf('\n', lineEndIdx + 1) ;
    }
    return lineEndIdx;
}

you can also improve it further...

vishal_aim
  • 7,636
  • 1
  • 20
  • 23
  • Code works :) but what if i want to also highlight line 2 and 3. How to achieve this? Thank you – Deathstar Jan 09 '13 at 08:13
  • May be this can help: http://stackoverflow.com/questions/3976616/how-to-find-nth-occurrence-of-character-in-a-string – vishal_aim Jan 09 '13 at 08:45
3

Use javax.swing.text.Utilities.getRowStart()/getRowEnd() to obtain the offsets for Highlighter

StanislavL
  • 56,971
  • 9
  • 68
  • 98