Applet
Applet is a program which needs another program to execute. Applet is a window (container) and is created by extending Applet class. In applets we can handle events using different Listeners. Applet has layout, it can be FlowLayout, BorderLayout etc. or layout can be set to null also. To execute applet, appletviewer is needed.
Inside the applet class, we put applet tag to specify name, width, height of the applet. First applet class is compiled with javac compiler, then appletviewer is used to run the applet.
Here Simple examples are provided to show how to create applet. Applet is execute in following manner, here, applet_test.java is name of applet.
import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code = 'applet_test' width=200 height =200> </applet> */ public class applet_test extends Applet implements ActionListener{ Button btn; TextField txt; public void init(){ setLayout(new BorderLayout()); btn = new Button("Click Me!"); txt = new TextField(20); add(btn,BorderLayout.NORTH); add(txt,BorderLayout.SOUTH); btn.addActionListener(this); } public void actionPerformed(ActionEvent aaaaa){ int num = Integer.parseInt(txt.getText()); if(num % 57 == 0){ txt.setText("It is divisible by 57"); }else { txt.setText("It is Nothing"); } } public void paint(Graphics g){ g.drawString("Easy on me", 20, 20); for(int i=0;i<20;i++) g.drawLine(i,i,1,1); } }
import java.applet.*; import java.awt.*; import javax.swing.*; import java.awt.event.*; /*<applet code = 'tt' width=300 height=300></applet>*/ public class tt extends JApplet implements ActionListener{ JLabel lbl; JTextField txt,txt1; ImageIcon ii; JButton btn; public void init(){ ii = new ImageIcon("img.png"); lbl = new JLabel("Image Test",ii,JLabel.CENTER);lbl.setBounds(20,20,100,25); txt = new JTextField(20);txt.setBounds(20,50,100,25); txt1 = new JTextField(20);txt1.setBounds(130,50,100,25); btn = new JButton("Click Me");btn.setBounds(20,80,100,25); setLayout(null); add(lbl); add(txt); add(txt1); add(btn); btn.addActionListener(this); setVisible(true); } public void actionPerformed(ActionEvent aa){ txt1.setText(txt.getText()); } public void paint(Graphics g){ g.drawString("Hello Applet",20,50); g.drawLine(20,20,200,200); g.drawRect(30,30,100,100); } }