Real'sHowTo AddThis Feed Button
Custom Search

Convert an Applet to Application Tag(s): Applet


Take this simple Applet
import java.applet.*;
import java.awt.*;

public class UnderlineText extends Applet{
  String s = "Java Howto";
  int x=20; 
  int y=50;

public void init() {
  add(new Button("Real's"));
}

public void paint(Graphics g) {
  g.drawString(s, x,y);
  g.drawLine(x , y+2 , x+getFontMetrics(getFont()).stringWidth(s) , y+2 );
  }
}
You use it with the following HTML
<HTML>
  <TABLE><TR><TD>
  <APPLET CODE=UnderlineText.class WIDTH=100 HEIGHT=100>
  </APPLET>
</HMTL>
To be able to use the same class as an application, we simply extend a Panel instead of an Applet, put it in Frame and call the init() method.
import java.awt.*;

public class UnderlineText extends Panel{
  String s = "Java Howto";
  int x=20; 
  int y=50;

public static void main(String[] args) {
  Frame f = new Frame();
  f.addWindowListener(new java.awt.event.WindowAdapter() {
       public void windowClosing(java.awt.event.WindowEvent e) {
       System.exit(0);
       };
     });

  UnderlineText ut = new UnderlineText();
  ut.setSize(100,100); // same size as defined in the HTML APPLET
  f.add(ut);
  f.pack();
  ut.init();
  f.setSize(100,100 + 20); // add 20, seems enough for the Frame title,
  f.show();
  }

public void init() {
  add(new Button("Real's"));
  }

public void paint(Graphics g) {
  g.drawString(s, x,y);
  g.drawLine(x , y+2 , x+getFontMetrics(getFont()).stringWidth(s) , y+2 );
  }
}

blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2014
[ home ]