itr*_*tro 1 java swing textarea position caret
可能重复:
自动滚动到文本区域的底部
我有TextArea组件.在不同的情况下,我应该向它添加文本.我希望Caret出现在新的附加文本的末尾,如果文本很大,则自动向下滚动.
textAreaStatus = new WebTextArea(
            "1- Click on the refresh icon to get newest file.\n" +
                    "2- Select destination if needed.\n" +
                    "3- Click download button to start downloading.\n");
    textAreaStatus.setBackground(Color.black);
    textAreaStatus.setCaretPosition(textAreaStatus.getText().length());
    textAreaStatus.getCaret().setVisible(true);
希望这段代码可能会以某种方式帮助您.你必须这样做
int len = textArea.getDocument().getLength();
textArea.setCaretPosition(len);
并且用于包装文本,以便向下滚动,因为长度超过实际视图的使用
textArea.setLineWrap(true);
这是一个示例程序供您理解
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class CarotPosition extends JFrame
{
    private JPanel panel;
    private JTextArea textArea;
    private JScrollPane scrollPane;
    private JButton button;
    public CarotPosition()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        panel = new JPanel();
        panel.setLayout(new BorderLayout());
        textArea = new JTextArea();
        scrollPane = new JScrollPane(textArea);
        textArea.setLineWrap(true);
        button = new JButton("Click to add Text");
        button.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent ae)
                {
                    textArea.append("Some NEW TEXT is here...");
                    int len = textArea.getDocument().getLength();
                    textArea.setCaretPosition(len);
                    textArea.requestFocusInWindow();
                }
            });
        setContentPane(panel);
        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(button, BorderLayout.PAGE_END);
        pack();
        setVisible(true);   
    }
    public static void main(String... args)
    {
        javax.swing.SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    new CarotPosition();
                }
            });
    }
}
希望这对你有所帮助.
问候
| 归档时间: | 
 | 
| 查看次数: | 7864 次 | 
| 最近记录: |