Question

I'm writing a ebook-reader program using java swing.
I read a txt file into a JTextArea.

JTextComponent.read(Reader in, Object desc). 

Thanks to @Andrew Thompson, Now I can use caret position to jump to specific positon in JTextArea. But I still don't know how to update the caret while navigating the text so I can save it as bookmarks.

I wrote some code to show my problem:

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;


public class MyProblem extends JFrame {

    public MyProblem() {
        JTextArea textArea = new JTextArea(20, 60);
        textArea.setEditable(false);
        String aLine = "Line number: ";
        String newLine = System.getProperty("line.separator");
        for (int i=0; i<20; i++) {
            textArea.insert(aLine + i + newLine, textArea.getDocument().getLength());
        }
        String problem = "When scrolling, how can set caret postion automatically on the first line of the viewport so I can save it?";
        textArea.append(problem);
        textArea.append(newLine);
        for (int i=21; i<39; i++) {
            textArea.insert(aLine + i + newLine, textArea.getDocument().getLength());
        }

        JScrollPane scrollPane = new JScrollPane(textArea);
        add(scrollPane);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new MyProblem().setVisible(true);
            }
        });
    }
}

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top