Delphi Clinic C++Builder Gate Training & Consultancy Delphi Notes Weblog Dr.Bob's Webshop
Hubert Klein Ikkink (aka Mr.Haki) - Communications Officer
 Mr.Haki's JBuilder Jar #12
See Also: JBuilder Papers

Invalidating our user interface
When we are developing Java applications and applets, we need to create user interfaces, so the application is able to interact with the user. But user interface programming has some pitfalls in Java. One of them is the updating of the user interface.

Suppose we want to create a very simple applet, containing a Label, TextField, and Button component. So we create an applet using the JBuilder Applet wizard. Go to the Visual Designer tab, set the layout of the applet to GridBagLayout, and add the components to the applet.
When we push the button, we want the text from the TextField, to be the new text of the Label component. We simply write this line of code in the event handler of the button:

  void button1_actionPerformed(ActionEvent e) {
    label1.setText(textField1.getText());
  }
This results in the following applet (complete source for this applet):

Screenshot
button pressed - no invalidate

But the result isn't quite what we would expect. The space the label occupies in the applet hasn't grown, but the text of the label is! We are only seeing the first part of the label, and not the whole text of the label.

We need to find a way to update the user interface of the applet, so the label will be assigned all space necessarry to show itself. This takes two more lines of code:

  void button1_actionPerformed(ActionEvent e) {
    label1.setText(textField1.getText());
    label1.invalidate();
    this.validate();
  }
The new lines indicate to the user interface update thread, that label1 has been changed and has become invalid. And then we invoke the validate() method of the applet, to force a revalidating of the applet, and this will result in an update of the applet. If we don't invalidate label1 first, the invokation of validate() will not matter, because the update thread will still think nothing has changed, and will therefore not update the user interface.

Here is a new applet with the extra lines of code added (complete source for this applet):

Screenshot
button pressed - with invalidate

And when we press the button now, we see the label is now totally visible and every component has been updated.

The applets have been tested using Netscape Communicator 4.5, and are working fine. So if above applets don't work, I would advise you to use Netscape Communicator 4.5.


This webpage © 1997-2009 by Bob Swart (aka Dr.Bob - www.drbob42.com). All Rights Reserved.