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.add(AppletDimension);
DimensionExample.setVisible(true);
DimensionExample.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void paint(Graphics g){
String str = "Hello Java";
g.setColor(Color.darkGray);
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("http://ecomputernotes.com", 200, 205);
//getSize() method for get applet size
Dimension dimension = getSize();
Font f = new Font("Arial",Font.BOLD,24);
g.setFont(f);
//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
g.drawString(str,x_coordinates,y_coordinates);
}
}