有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing如何在java中的textArea中新添加的文本末尾自动显示插入符号?

Possible Duplicate:
Automatically scroll to the bottom of a text area

我有TextArea组件。在不同的情况下,我应该附加文本。我希望插入符号出现在新附加文本的末尾,如果文本太大,则自动向下滚动

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);

共 (1) 个答案

  1. # 1 楼答案

    希望这段代码能对您有所帮助。你必须这么做

    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();
                    }
                });
        }
    }
    

    希望这对你有所帮助

    问候