Generally, when embedding a Java applet into an HTML page, the size of the applet is determined by two attributes width and height of the <applet> tag. For example:

<applet

	id="myApplet"

	code="MyApplet.class"

	width="640" height="480"
	>
</applet>
That code will set the applet’s size to 640 by 480 pixels. However that size is fixed, so when users resize their browser’s window, the applet’s size does not get updated accordingly.

To get the applet resized automatically when the users resize browser’s window, we can use relative value (percentage) for the width and height attributes. For example:

<applet

	id="myApplet"

	code="MyApplet.class"

	width="80%" height="80%"
	>
</applet>
That will set the applet’s size about 80 percent of the browser’s size. So when the browser’s window is being resized, the applet’s size gets updated accordingly (so the specified percentage is always kept). If we want the applet fits the display area in browser’s window, use the maximum percentage value:

width="100%" height="100%"
Following is code of the sample HTML page:

<html>
	<head>
		<title>Resizable Java applet</title>
	</head>
	<body top="0" left="0">
		<center>
			<applet id="ResizableApplet"
				code="ResizableApplet.class"

				width="100%" height="100%"
					>
			</applet>
		</center>
	</body>
</html>
And code of the sample applet:

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

public class ResizableApplet extends JApplet {
	public void init() {
		getContentPane().setBackground(Color.GREEN);
	}
}
This applet simply shows a green background like this:

resizable applet

Try to resize the browser’s window and we’ll see the applet get resized accordingly.



 

Other Java Applet Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (ResizableApplet.zip)ResizableApplet.zip[Applet source code and HTML page]1 kB

Add comment