by Dinesh Thakur Category: AWT and Applets

Eample AppletDimension print center aligned text "Hello Java" This Java example 'How to Set the Dimension of the Applet' shows how to print a string in center of an applet screen window using the Dimension class.

In the Following example AppletDimension shows How to Set the Dimension of the Applet using getSize(),getFontMetrics() method. The Syntax for getting X coordinates are

x_coordinates = dimension.width/2 - fontmetrics.stringWidth(str)/2 and The Syntax for getting Y coordinates are y_coordinates = dimension.height/2 - fontmetrics.getHeight()/2;

Here is the java code for the program AppletDimension Example :.


import java.applet.Applet;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.*;
public class AppletDimension extends Applet{
public static void main(String[] args) {
Frame DimensionExample = new Frame("How to Set the Dimension of the Applet");
DimensionExample.setSize(350, 250);
Applet AppletDimension = new AppletDimension();
DimensionExample.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
                   public void paint(Graphics g){
                    String str = "Hello Java";
                    g.setFont(new Font("Arial",Font.BOLD,14));
                    g.drawString("How to Set the Dimension of the Applet ", 50, 40);
                    g.setFont(new Font("Arial",Font.BOLD,10));
                    g.drawString("", 200, 205);
                    //getSize() method for get applet size
                    Dimension dimension = getSize();
                    Font f = new Font("Arial",Font.BOLD,24);
                    //get x and y coordinates of screen
                    int x_coordinates,y_coordinates;
                    FontMetrics fontmetrics = g.getFontMetrics();
                    x_coordinates = dimension.width/2 - fontmetrics.stringWidth(str)/2;
                    y_coordinates = dimension.height/2 - fontmetrics.getHeight()/2;
                    //print string at specified location using drawString method


How to Set the Dimension of the Applet

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles