Java学习笔记之JTextArea自动滚动到最后一行

实现文本区文本自动显示到最后一行:

JTextArea jta = new JTextArea(5,10);

jta .selectAll();
jta .setCaretPosition(textPane.getSelectedText().length());
jta .requestFocus();


 

下面是一个参考示例:

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

public class Demo extends JFrame {
 JTextPane textPane = new JTextPane();
 JTextArea ja = new JTextArea();

 public Demo() {
  super("JTextPane Demo");
  getContentPane().setLayout(new BorderLayout());
  final JButton buttonHome = new JButton("Go to Home");
  final JButton buttonEnd = new JButton("Go to End");

  ActionListener positionHandler = new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    if (e.getSource() == buttonHome) {
     textPane.setCaretPosition(0);
     textPane.requestFocus();
    } else if (e.getSource() == buttonEnd) {
     textPane.selectAll();
     textPane.setCaretPosition(textPane.getSelectedText()
       .length());
     textPane.requestFocus();
    }
   }
  };
  buttonHome.addActionListener(positionHandler);
  buttonEnd.addActionListener(positionHandler);

  JPanel paneNorth = new JPanel();
  JPanel paneSouth = new JPanel();

  paneSouth.add(buttonHome);
  paneSouth.add(buttonEnd);

  getContentPane().add(paneSouth, BorderLayout.SOUTH);

  paneNorth.setLayout(new BorderLayout());
  paneNorth.add(new JScrollPane(textPane), BorderLayout.CENTER);
  getContentPane().add(paneNorth, BorderLayout.CENTER);

  setSize(300, 400);
  show();

 }

 public static void main(String[] args) {
  Demo app = new Demo();
  app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
}

你可能感兴趣的:(Java学习笔记之JTextArea自动滚动到最后一行)