我有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);
答案 0 :(得分:6)
希望这段代码可能会以某种方式帮助您。你只需要这样做
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();
}
});
}
}
希望这对你有所帮助。
此致