Google Tag Manager

2022/09/30

Make the editable JTextArea scrollable beyond its last line

Code

// https://stackoverflow.com/questions/36715803/scrolling-past-the-end-in-idea
// IntelliJ IDEA: Settings -> Editor -> General -> Check Show virtual space at file bottom
JTextArea textArea = new JTextArea() {
  // https://stackoverflow.com/questions/32679335/java-jtextarea-allow-scrolling-beyond-end-of-text
  @Override public Dimension getPreferredSize() {
    Dimension d = super.getPreferredSize();
    Container c = SwingUtilities.getAncestorOfClass(JScrollPane.class, this);
    if (c instanceof JScrollPane && isEditable()) {
      Rectangle r = ((JScrollPane) c).getViewportBorderBounds();
      d.height += r.height - getRowHeight() - getInsets().bottom;
    }
    return d;
  }
};

References