Sunday, November 27, 2011

Using Applet dimension to print center aligned text Example


  1. /*
  2. Using Applet dimension to print center aligned text Example
  3. This Java example shows how to print text in center of an applet window using
  4. Dimension class.
  5. */
  6.  
  7. import java.applet.Applet;
  8. import java.awt.Dimension;
  9. import java.awt.Font;
  10. import java.awt.FontMetrics;
  11. import java.awt.Graphics;
  12.  
  13. /*
  14. <applet code = "AppletDimensionExample" width = 500 height = 300>
  15. </applet>
  16. */
  17.  
  18. public class AppletDimensionExample extends Applet{
  19.  
  20. public void paint(Graphics g){
  21. int x,y;
  22. String s = "Hello World";
  23.  
  24. //get applet size using getSize method
  25. Dimension d = getSize();
  26. Font f = new Font("Arial",Font.BOLD,24);
  27. g.setFont(f);
  28.  
  29. //determine x and y coordinates
  30. FontMetrics fm = g.getFontMetrics();
  31. x = d.width/2 - fm.stringWidth(s)/2;
  32. y = d.height/2 - fm.getHeight();
  33.  
  34. //print string at specified location using drawString method
  35. g.drawString(s,x,y);
  36. }
  37. }

No comments:

Post a Comment

How to find the most appropriate Keywords?

  🔍 Step 1: Understand Your Business and Audience Define your products, services, or content . Identify your target audien...