简体   繁体   English

如何使JTextArea移动滚动条

[英]How to make a JTextArea moving the scrollbar

I am working with Java Swing and I have put a JTextArea in a JScrollBar. 我正在使用Java Swing,我已将JTextArea放在JScrollBar中。 What I want is the scrollbar to follow the data. 我想要的是跟踪数据的滚动条。 For a example i want to write in the JTextArea the output of a for(;;) so i can see the latest (newest) values. 举个例子,我想在JTextArea中写一个for(;;)的输出,这样我就能看到最新的(最新的)值。 How could I do that? 我怎么能这样做?

EDIT: I have edited the question to be more specific. 编辑:我已经编辑了更具体的问题。

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

public class AutoScrollTextArea {

    static String text = "Lorem ipsum dolor sit amet, "
        +"consectetur adipiscing elit. "
        +"Integer vestibulum metus id elit malesuada mattis. "
        +"Aliquam non rutrum justo. Morbi eleifend nisi ut "
        +"turpis commodo nec ultricies arcu vehicula. "
        +"Donec varius neque at nunc pellentesque tincidunt. "
        +"Phasellus sed ante ut tortor fermentum posuere sed "
        +"sit amet tortor. Sed cursus magna a lacus mattis eleifend. "
        +"Aliquam congue faucibus purus vel commodo. "
        +"Fusce rutrum consectetur nibh nec facilisis. ";

    public static void main(String[] args) {

        Runnable r = new Runnable() {
            public void run() {
                JPanel gui = new JPanel(new BorderLayout(5,5));
                final JTextArea textArea = new JTextArea(10,60);
                textArea.setWrapStyleWord(true);
                textArea.setLineWrap(true);
                textArea.setEnabled(false);
                gui.add(new JScrollPane(textArea), BorderLayout.CENTER);

                JButton button = new JButton("Add Text");
                button.addActionListener( new ActionListener(){
                    public void actionPerformed(ActionEvent ae) {
                        textArea.append(text);
                        textArea.append(System.getProperty("line.separator"));
                        textArea.append(System.getProperty("line.separator"));
                    }
                } );
                gui.add(button, BorderLayout.SOUTH);

                JOptionPane.showMessageDialog(null, gui);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

( It happens automatically ;) (它自动发生;)

IF you are using JTextArea in JScrollPane then following should work: 如果您在JScrollPane中使用JTextArea,那么以下应该工作:

JTextArea area = new JTextArea();
area.setWrapStyleWord(true);
area.setLineWrap(true);
JScrollPane pane = new JScrollPane(area);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM