Home > Software design >  How can I center a text vertically within a JTextArea?
How can I center a text vertically within a JTextArea?

Time:01-11

I have a JTextArea with a long text. In the text there is the string "abc" that I want to be displayed in the middle (vertical) of the text area. I can use setCaretPosition to cause the ScrollPane to scroll enough for the string "abc" to scroll into view. The scrolling continues until the text "abc" becomes visible at the bottom of the text area (see example) How can I get the scrollbar to scroll so far that the text "abc" is displayed in the middle (vertically) in the visible area?

many thanks for your help!

public class TestCenter {

    public TestCenter() {
        JFrame frame = new JFrame();
        JTextArea ta = new JTextArea();

        frame.setMinimumSize(new Dimension(800, 600));
        frame.add(new JScrollPane(ta));
        frame.pack();
        frame.setVisible(true);

        SwingUtilities.invokeLater(() -> {
            StringBuilder testText = new StringBuilder();
            for (int t = 0; t < 100; t  ) {
                testText.append("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
            }
            testText.append("abc");
            for (int t = 0; t < 100; t  ) {
                testText.append("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
            }
            ta.setText(testText.toString());
            ta.setCaretPosition(testText.indexOf("abc"));
        });
    }

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

}

CodePudding user response:

To move the scroll bar to the position of the abc text to be displayed vertically in the middle of the enter image description here

  • Related