Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
May 19, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Refresh Component Displays

When you create the visual components that make up a user interface, their size and position are usually constant. However, it's sometimes necessary to change a component's size or position dynamically based on some user action. For example, your application may change the text in a label that is already displayed. If the label is too small to show the entire string, you might need to refresh the display so that the label will be resized. To refresh the display of components in a container subclass such as a frame or panel, you should call the container's invalidate() and validate() methods.
import java.awt.*;
import java.awt.event.*;
public class Validation extends Frame implements ActionListener {
	Button button;
	public static void main(String[] args) {
		Validation v = new Validation();
		v.setSize(400, 300);
	}  //  public static void main(String[] args)
	public Validation() {
		setLayout(new FlowLayout());
		button = (Button)add(new Button("Short Label"));
	}  //  public Validation()
	public void actionPerformed(ActionEvent event) {
		button.setLabel("This is a much longer label");
	}  //  public void actionPerformed()
}  //  public class Validation extends Frame
Running this code will display a frame that contains a button, and pressing it will change the button's label and cause it to be resized. However, if you remove the call to invalidate() and/or validate(), the button's text will change while its size remains the same. The invalidate() method marks the container (in this case, the frame subclass) as needing to be refreshed (or "laid out"), while the validate() method actually performs the refresh operation.
Brett Spell
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date