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);		v.setVisible(true);	}  //  public static void main(String[] args)	public Validation() {		setLayout(new FlowLayout());		button = (Button)add(new Button("Short Label"));		button.addActionListener(this);	}  //  public Validation()	public void actionPerformed(ActionEvent event) {		button.setLabel("This is a much longer label");		invalidate();		validate();	}  //  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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: