Mechanisms of setText() in JTextArea?

2019-02-27 00:04发布

问题:

I try to show some text in my JTextArea in runtime. But when I use a loop of setText to show text in order, it only show the text of the last loop Here is my code:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
 for (int i=0;i<10;i++)
     jTextArea1.setText("Example "+i);
}                                        

I want it to show "Example 1", "Example 2",..,"Example 9". But it only show one time "Example 9"

Anyone can explain it for me??

回答1:

setText does just that, it "sets the text" of field to the value your provide, removing all previous content.

What you want is JTextArea#append

If you're using Java 8, another option might be StringJoiner

StringJoiner joiner = new StringJoiner(", ");
for (int i = 0; i < 10; i++) {
    joiner.add("QUang " + i);
}
jTextArea1.setTexy(joiner.toString());

(assuming you want to replace the text each time the actionPerformed method is called, but you can still use append)

Update based on assumptions around comments

I "assume" you mean you want each String to be displayed for a short period of time and then replaced with the next String.

Swing is a single threaded environment, so anything that blocks the Event Dispatching Thread, like loops, will prevent the UI from been updated. Instead, you need to use a Swing Timer to schedule a callback at regular intervals and make change the UI on each tick, for example.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private String[] messages = {
            "Example 1",
            "Example 2",
            "Example 3",
            "Example 4",
            "Example 5",
            "Example 6",
            "Example 7",
            "Example 8",
            "Example 9",
        };

        private JTextArea ta;
        private int index;

        private Timer timer;

        public TestPane() {
            setLayout(new BorderLayout());
            ta = new JTextArea(1, 20);
            add(new JScrollPane(ta));

            JButton btn = new JButton("Start");
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (timer.isRunning()) {
                        timer.stop();
                    }
                    index = 0;
                    timer.start();
                }
            });
            add(btn, BorderLayout.SOUTH);

            timer = new Timer(500, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (index < messages.length) {
                        ta.setText(messages[index]);
                    } else {
                        timer.stop();
                    }
                    index++;
                }
            });
        }

    }

}

Have a look at Concurrency in Swing and How to use Swing Timers for more details