The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
January 2002

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

problem refreshing/updating a JTextField

Posted by David Fashena on January 29, 2002 at 5:39 PM

Hello All,

I have a question about how to update/refresh text components in an applet.

Appended below is a small test applet that approximates Pi numerically. There are two JTextFields, one that is used to input a number of iterations and a second one to show the result.

Because the calculation can take a while, I would like the result JTextField to show "Working" while the calculation is proceeding, and then to show the numerical result when it has been computed.

However, I can't figure out how to update the JTextField before the calculation is done. I include the source below. Thanks in advance for any ideas!

// // width = 500 height = 50>

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

public class Pi_applet2 extends JApplet implements ActionListener {

public JTextField its_jtf = new JTextField(null, 20);
public JTextField pi_jtf = new JTextField(null, 20);

JPanel pane = new JPanel();

double pi_est;

public void init() {
its_jtf.addActionListener(this);
pane.setLayout(new GridLayout(1,2));
pane.add(its_jtf);
pane.add(pi_jtf);
setContentPane(pane);
this.setVisible(true);
}

public void actionPerformed(ActionEvent e) {
double pi_est=0.0;
int its;

// ****** the text "Working..." never appears:
// ( why not??)
pi_jtf.setText("Working...");

String num_str = its_jtf.getText(); // get # of iterations
its = Integer.parseInt(num_str);
pi_est = crunch(its); // do the calculation
pi_jtf.setText(Double.toString(pi_est));
}

public double crunch(int max) {
// numerical estimate of Pi
double b = 1.0, s= 0.0, FOUR = 4.0,fm;
int n, flip = 1;
for (n=0; n< max; n++) {
s += flip*FOUR/b;
b = b+2.0;
flip *= -1;
}
return(s);
}

}





Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us