Saturday 15 October 2016

Swing applets



·         Swing-based Applets are similar to AWT-based Applets, but with an important difference: A Swing applet extends JApplet rather than Applet. JApplet is derived from Applet. Thus it includes all of the functionality found in Applet and add support for Swing. JApplet is a top-level Swing container, which means that it is not derived from JComponent.
·         Swing Applets uses the four lifecycle methods: init(), start(), stop(), and destroy(). We have to override only those methods that are needed by our applet.
·         Painting is accomplished differently in Swing than it is in the AWT, and a Swing Applet will not normally override the paint() method.
·         All interactions with components in a Swing Applet must take place on the event dispatching thread.
·         Example:
AppletSwing.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AppletSwing extends JApplet
{
 JButton b1;
 JLabel jbl;
 public void init()
 {
   try {
      SwingUtilities.invokeAndWait(new Runnable(){
      public void run()
      {
       makeGUI();
      }
     });
   }catch(Exception e)
     {
        System.out.println("Error Occured "+e);
     }
  }
  private void makeGUI()
 {
   setLayout(new FlowLayout());
   b1=new JButton("Button1");
    b1.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e)
   {
     jbl.setText("Button 1 is pressed");
   }
  });
 add(b1);
jbl=new JLabel("Press a button");
  add(jbl);
 }
}

SwingApplet.html
<html>
<head>
<body>
<applet code="AppletSwing.class"
        width=200
        height=200 >
</applet>
</body>
</html>

                      

·         Swing Applets must use invokeAndWait() rather than invokeLater() because the init() method must not return until the entire initialization process has been completed.

No comments:
Write comments