问题
Let's say I have a JTextField "status" and I'm running this code:
status = new JTextField(50);
add(status);
for (int i=0; i<10000; i++) {
status.setText("bla bla - "+ i);
System.out.println("bla bla - "+ i);
}
My problem is that right now while the loop is running nothing happened in the JTextField's text and only when the loop end the label is "bla bla - 10000".
I want to make something like a status bar but cant update this status bar "online". I also tried to do the update in a thread but ended with the same result.
Can someone show my how I can present a text in a GUI while iterating or looping?
回答1:
Use a SwingWorker to split UI-update and long running tasks.
Take a few minutes to read the end of the Swing tag wiki and follow the provided links.
Here is a small example of such code:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class TestSwingWorker {
private JTextField progressTextField;
protected void initUI() {
final JFrame frame = new JFrame();
frame.setTitle(TestSwingWorker.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Clik me to start work");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
doWork();
}
});
progressTextField = new JTextField(25);
progressTextField.setEditable(false);
frame.add(progressTextField, BorderLayout.NORTH);
frame.add(button, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
protected void doWork() {
SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>() {
@Override
protected Void doInBackground() throws Exception {
for (int i = 0; i < 100; i++) {
// Simulates work
Thread.sleep(10);
publish(i);
}
return null;
}
@Override
protected void process(List<Integer> chunks) {
progressTextField.setText(chunks.get(chunks.size() - 1).toString());
}
@Override
protected void done() {
progressTextField.setText("Done");
}
};
worker.execute();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestSwingWorker().initUI();
}
});
}
}
回答2:
Use a javax.swing.Timer. Here is an example that shows you how:
private void refreshMyTextField() {
Timer timer1 = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jTextField1.setText("bla bla - "+(j++));
}
});
timer1.start();
}
回答3:
Use Timer class which executes a task in intervals. Because you don't use interval, what you get is the last value 10000. You can't see previous values because of interval absence.
Regards,
回答4:
try to use status.setText("");
before status.setText("bla bla - "+ i);
来源:https://stackoverflow.com/questions/16010990/changing-jtextfields-text-while-iterating-or-inside-a-loop