Java Applet Text in Center
How to display your message or text in the center of Applet. This kind of questions are most frequently asked in the examinations. Here is the example of the same with details. In the example what I have did is that first i searched for the maximum value of the height and width then i have divided that values by two to find out exact center value and than after i have subtracted the length of the string to find exact left value for the string.
<applet code="Applet2.class" height="300" width="300"></applet>
public class Applet2 extends Applet
public void paint(Graphics g)
Dimension dimsize = this.getSize();
String s = "Java Applet Text in Center";
g.drawString( s,(dimsize.width/2)-(s.length()), dimsize.height/2);
To find out the exact size of the applet you have to use getSize() method, getSize() in Applet will return the dimensions of the Applet, ie. Total Size of the Applet. Now you have to find out Height and width from that object using width and height method to know the height and width of the Applet Screen. Finally You need to divide Height and Width by 2 to get exact Center Point to display our text “Java Applet Text in Center”.