Thursday, November 18, 2010

How to create a swing applet and application in eclipse

What are applets in java?
Applets are not  stand-alone programs.They run within either a web browser or applet viewer. Applet is included in html page using <applet>. See a applet example here.

What is swing in java?
 swing can be used as stand-alone and also as a applet.
Lets start a swing applet.Before that just have a look at simple swing stand-alone program.
Now start Eclipse IDE. See here how to start an eclipse 
A swing applet program
/*

import java.awt.*;
import javax.swing.*; 
/* 
/* <applet code="SwingApplet" height=300 width=300>
 </applet>
*/
*/ 
public class SwingApplet extends JApplet{
JLabel jlab;
public void init(){
try{
SwingUtilities.invokeAndWait(new Runnable(){
public void run(){
swingGUI();
}
});
}
catch(Exception e){
System.out.println(e);
}
}
private void swingGUI(){
jlab=new JLabel("Select which is useful");
//set layout
setSize(300,300);
 setLayout(new FlowLayout());
add(jlab);
}
}
*/
NOTE: The two comments which are underlined above near <applet  should be removed, to execute.

Explaining:
           For swing applet JApplet is extended and swing package is imported. 
Here thread is invoked after calling the method, using invokeAnd Wait().Where as in swing invokeLater() is used.
try and catch blocks are used to catch any exception.

How to run swing applet?
After completing your program in Eclipse IDE you need to save it, and then press Alt+shift You will get option in small box select according to your program type, here select Applet application.
 Applet will start.

2 comments:

  1. I would like to see a working example of how to run a java program as an Applet or Application

    ReplyDelete
  2. ASP.net and Java have been the most successful languages in the 4th generation languages that have evolved over the years. Programmers have the edge of developing programs that much faster than any language. There are several advantages that both languages hold together to give them an edge over their predecessors.

    .net obfuscator

    ReplyDelete