java小程序
An applet is a special kind of Java program that runs in a Java enabled browser. This is the first Java program that can run over the network using the browser. Applet is typically embedded inside a web page and runs in the browser.
小程序是一种特殊的Java程序,可在支持Java的浏览器中运行。 这是第一个可以使用浏览器通过网络运行的Java程序。 Applet通常嵌入在网页内,并在浏览器中运行。
In other words, we can say that Applets are small Java applications that can be accessed on an Internet server, transported over Internet, and can be automatically installed and run as apart of a web document.
换句话说,我们可以说Applets是小型Java应用程序,可以在Internet服务器上进行访问,通过Internet进行传输,并且可以作为Web文档的一部分自动安装和运行。
After a user receives an applet, the applet can produce a graphical user interface. It has limited access to resources so that it can run complex computations without introducing the risk of viruses or breaching data integrity.
用户收到小程序后,小程序可以生成图形用户界面。 它对资源的访问受到限制,因此它可以运行复杂的计算而不会带来病毒或破坏数据完整性的风险。
To create an applet, a class must class extends java.applet.Applet class.
要创建小程序,一个类必须扩展java.applet.Applet类。
An Applet class does not have any main() method. It is viewed using JVM. The JVM can use either a plug-in of the Web browser or a separate runtime environment to run an applet application.
Applet类没有任何main()方法。 使用JVM查看。 JVM可以使用Web浏览器的插件或单独的运行时环境来运行applet应用程序。
JVM creates an instance of the applet class and invokes init() method to initialize an Applet.
JVM创建applet类的实例,并调用init()方法来初始化Applet。
Note: Java Applet is deprecated since Java 9. It means Applet API is no longer considered important.
注意:从Java 9开始不推荐使用Java Applet。这意味着Applet API不再重要。
Java Applet的生命周期 (Lifecycle of Java Applet)
Following are the stages in Applet
以下是Applet中的阶段
Applet is initialized. Applet已初始化。 Applet is started 小程序已启动 Applet is painted. Applet已绘制。 Applet is stopped. 小程序已停止。 Applet is destroyed. 小程序被破坏。
一个简单的小程序 (A Simple Applet)
import java.awt.*;
import java.applet.*;
public class Simple extends Applet
{
public voidpaint(Graphics g)
{
g.drawString("A simple Applet", 20, 20);
}
}
Every Applet application must import two packages - java.awt and java.applet.
每个Applet应用程序都必须导入两个包java.awt和java.applet 。
java.awt.* imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user (either directly or indirectly) through the AWT. The AWT contains support for a window-based, graphical user interface. java.applet.* imports the applet package, which contains the class Applet. Every applet that you create must be a subclass of Applet class.
java.awt.*导入Abstract Window Toolkit(AWT)类。 小程序通过AWT与用户互动(直接或间接)。 AWT包含对基于窗口的图形用户界面的支持。 java.applet.*导入applet包,其中包含类Applet。 您创建的每个小程序都必须是Applet类的子类。
The class in the program must be declared as public, because it will be accessed by code that is outside the program.Every Applet application must declare a paint() method. This method is defined by AWT class and must be overridden by the applet. The paint() method is called each time when an applet needs to redisplay its output. Another important thing to notice about applet application is that, execution of an applet does not begin at main() method. In fact an applet application does not have any main() method.
程序中的类必须声明为public,因为它将由程序外部的代码访问。每个Applet应用程序都必须声明paint()方法。 此方法由AWT类定义,并且必须由applet覆盖。 每当applet需要重新显示其输出时,都会调用paint()方法。 关于applet应用程序的另一个重要注意事项是,applet的执行不是从main()方法开始的。 实际上,小应用程序应用程序没有任何main()方法。
小程序的优点 (Advantages of Applets)
It takes very less response time as it works on the client side. 由于它在客户端工作,因此响应时间非常短。 It can be run on any browser which has JVM running in it. 它可以在运行JVM的任何浏览器上运行。
小程序类 (Applet class)
Applet class provides all necessary support for applet execution, such as initializing and destroying of applet. It also provide methods that load and display images and methods that load and play audio clips.
Applet类为applet执行提供了所有必要的支持,例如applet的初始化和销毁。 它还提供了加载和显示图像的方法以及加载和播放音频剪辑的方法。
小程序骨骼 (An Applet Skeleton)
Most applets override these four methods. These four methods forms Applet lifecycle.
大多数小程序都覆盖这四种方法。 这四种方法形成Applet生命周期。
init() : init() is the first method to be called. This is where variable are initialized. This method is called only once during the runtime of applet. init(): init()是第一个要调用的方法。 这是初始化变量的地方。 在applet运行期间,此方法仅被调用一次。 start() : start() method is called after init(). This method is called to restart an applet after it has been stopped. start():在init()之后调用start()方法。 停止该小程序后,将调用此方法以重新启动它。 stop() : stop() method is called to suspend thread that does not need to run when applet is not visible. stop():调用stop()方法来挂起在小程序不可见时不需要运行的线程。 destroy() : destroy() method is called when your applet needs to be removed completely from memory. destroy()方法:当完全从内存中删除您的小程序的需求destroy()方法被调用。
Note: The stop() method is always called before destroy() method.
注意:总是在destroy()方法之前调用stop()方法。
小程序骨架的示例 (Example of an Applet Skeleton)
import java.awt.*;
import java.applet.*;
public class AppletTest extends Applet
{
public voidinit()
{
//initialization
}
public void start ()
{
//start or resume execution
}
public void stop()
{
//suspend execution
{
public void destroy()
{
//perform shutdown activity
}
public void paint (Graphics g)
{
//display the content of window
}
}
小程序示例 (Example of an Applet)
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
int height, width;
public void init()
{
height = getSize().height;
width = getSize().width;
setName("MyApplet");
}
public void paint(Graphics g)
{
g.drawRoundRect(10, 30, 120, 120, 2, 3);
}
}
Applet中的参数 (Parameter in Applet)
User-define Parameter can be applied in applet using tags. Each tag has a name and value attribute.
用户定义的参数可以使用标签在applet中应用。 每个标记都有一个名称和值属性。
例: (Example:)
name = color
Value = red
句法: (Syntax:)
In an applet code, applet can refer to a parameter by its name and then find its value.
在applet代码中,applet可以通过名称来引用参数,然后找到其值。
The two most important thing to handle and set up the parameter is the tag in the HTML document and an applet code to parse this parameter.
处理和设置参数的两个最重要的事情是HTML文档中的标记和解析该参数的小程序代码。
init() method is used to get hold of the parameters which is defined in the tags. And getParameter() method is used for getting the parameters.
init()方法用于获取在标记中定义的参数。 getParameter()方法用于获取参数。
In Applet, Parameters are passed on applet when it is loaded.
在Applet中,参数在加载时在applet上传递。
例: (Example:)
param.java
param.java
import java.applet.*;
import java.awt.*;
public class param extends Applet
{
String str;
public void init()
{
str=getParameter("pname");
if (str == null)
str = "Welcome to studytonight.com";
str = "Hello " + str;
}
public void paint(Graphics g)
{
g.drawString(str, 200, 200);
}
}
param.html
param.html
如何运行小程序 (How to run an Applet Program)
An Applet program is compiled in the same way as you have been compiling your console programs. However there are two ways to run an applet.
用与编译控制台程序相同的方式来编译Applet程序。 但是,有两种运行小程序的方法。
Executing the Applet within Java-compatible web browser. 在Java兼容的Web浏览器中执行Applet。 Using an Applet viewer, such as the standard tool, applet viewer. An applet viewer executes your applet in a window 使用小程序查看器(例如标准工具)。 小程序查看器在窗口中执行小程序
For executing an Applet in an web browser, create short HTML file in the same directory. Inside body tag of the file, include the following code. (applet tag loads the Applet class)
要在Web浏览器中执行Applet,请在同一目录中创建简短的HTML文件 。 在文件的主体标签中,包括以下代码。 ( applet标签加载Applet类)
< applet code = "MyApplet" width=400 height=400 >
< /applet >
运行HTML文件 (Run the HTML file)
使用Applet Viewer运行Applet (Running Applet using Applet Viewer)
To execute an Applet with an applet viewer, write short HTML file as discussed above. If you name it as run.htm, then the following command will run your applet program.
要使用小程序查看器执行小程序,请如上所述编写简短HTML文件。 如果将其命名为run.htm ,那么以下命令将运行您的applet程序。
f:/>appletviewer run.htm
Applet中的图形 (Graphics in Applet)
In Applet, java.awt.Graphicsclass provides methods for using graphics.
在Applet中,java.awt.Graphicsclass提供了使用图形的方法。
Below are the Methods of the Graphics class.
下面是Graphics类的Methods。
Sr No.MethodsDescription1public abstract void drawString(String str, int x, int y)Used to draw specified string.2public void drawRect(int x, int y, int width, int height)Used to draw a rectangle of specified width and height.3public abstract void fillRect(int x, int y, int width, int height)Used to draw a rectangle with a default colourof specified width and height.4public abstract void drawOval(int x, int y, int width, int height)Used to draw oval of specified width and height.5public abstract void fillOval(int x, int y, int width, int height)Used to draw oval with a default colour of specified width and height.6public abstract void drawLine(int x1, int y1, int x2, int y2)Used for drawing lines between the point (x1, x1) and (x2, y2).7public abstract booleandrawImage(Image img, int x, int y, ImageObserver observer)Used for drawing a specified image.8public abstract void drawArc(int x, int y, int width, int height, intstartAngle, intarcAngle)Used for drawing a circular arc.9public abstract void fillArc(int x, int y, int width, int height, intstartAngle, intarcAngle)Used for filling circular arc.10public abstract void setColor(Color c)Used to set a colour to the object.11public abstract void setFont(Font font)Used to set font.
高级 方法 描述 1个 公共抽象无效drawString(String str,int x,int y) 用于绘制指定的字符串。 2 public void drawRect(int x,int y,int width,int height) 用于绘制指定宽度和高度的矩形。 3 公共抽象void fillRect(int x,int y,int width,int height) 用于绘制具有指定宽度和高度的默认颜色的矩形。 4 公共抽象无效drawOval(int x,int y,int width,int height) 用于绘制指定宽度和高度的椭圆。 5 公共抽象void fillOval(int x,int y,int width,int height) 用于绘制具有指定宽度和高度的默认颜色的椭圆形。 6 公共抽象无效drawLine(int x1,int y1,int x2,int y2) 用于在点(x1,x1)和(x2,y2)之间绘制线。 7 公共抽象booleandrawImage(图像img,int x,int y,ImageObserver观察器) 用于绘制指定的图像。 8 公共抽象无效drawArc(int x,int y,int width,int height,intstartAngle,intarcAngle) 用于绘制圆弧。 9 公共抽象void fillArc(int x,int y,int width,int height,intstartAngle,intarcAngle) 用于填充圆弧。 10 公共抽象无效setColor(Color c) 用于为对象设置颜色。 11 公共抽象无效setFont(字体) 用于设置字体。
例: (Example:)
GraphicsDemo1.java
GraphicsDemo1.java
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo1 extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.black);
g.drawString("Welcome to studytonight",50, 50);
g.setColor(Color.blue);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
g.drawLine(21,31,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
}
}
GraphicsDemo1.html
GraphicsDemo1.html
在Applet中处理图像 (Working with Images in Applet)
In Applet programs, images also can be used
在Applet程序中,也可以使用图像
java.awt.Image class is used for representing an image.
java.awt.Image类用于表示图像。
java.applet, java.awt and java.awt.image are the packages which are used for event handling.
java.applet,java.awt和java.awt.image是用于事件处理的包。
加载图像 (Loading an image)
In Applet, images are loaded using getImage() method. This method works when the constructor of the Applet is called. It is always suggested to call the constructor in init() method.
在Applet中,使用getImage()方法加载图像。 调用Applet的构造函数时,此方法有效。 始终建议在init()方法中调用构造函数。
Here are some examples:
这里有些例子:
Image image1 = getImage(getCodeBase(), "image1.gif"); Image image2 = getImage(getDocumentBase(), "image1.jpeg"); Image image3 = getImage(new URL("http://java.sun.com/graphics/image.gif"));
图片image1 = getImage(getCodeBase(),“ image1.gif”); 图片image2 = getImage(getDocumentBase(),“ image1.jpeg”); 图片image3 = getImage(新的URL(“ http://java.sun.com/graphics/image.gif”));
显示影像 (Displaying an image)
In Applet, images are displayed using drawImage() method. This method is supplied by the Graphics object, which is passed to paint() method.
在Applet中,使用drawImage()方法显示图像。 此方法由Graphics对象提供,并传递给paint()方法。
例: (Example:)
Aimage.java
Aimage.java
import java.awt.*;
import java.applet.*;
public class Aimage extends Applet
{
Image img1;
public void init()
{
img1=getImage(getDocumentBase(),"icon.png");
}
public void paint(Graphics g)
{
g.drawImage(img1,100,100,this);
}
}
Aimage.html
Aimage.html
Applet中的事件处理 (EventHandling in Applet)
In Applet we can also perform event handling.
在Applet中,我们还可以执行事件处理。
Below is an example of event handling which prints a message when clicked on the button.
下面是事件处理的示例,单击该按钮时将显示一条消息。
例: (Example:)
EventAppletDemo.java
EventAppletDemo.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventAppletDemo extends Applet implements ActionListener
{
Button b1;
TextField tf1;
public void init()
{
tf1=new TextField();
tf1.setBounds(30,40,200,20);
b1=new Button("Click");
b1.setBounds(80,150,60,50);
add(b1);
add(tf1);
b1.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e)
{
tf1.setText("Welcome to studytonight");
}
}
Myapplet.html
Myapplet.html
小程序中的动画 (Animation in Applet)
In Applet, we can also create animations in a program using a gif image. Below is an example in which drawImage() method is used which is of Graphics class, it is used for displaying an image.
在Applet中,我们还可以使用gif图像在程序中创建动画。 下面是一个示例,其中使用了Graphics类的drawImage()方法,该方法用于显示图像。
Note: Download a gif file for the below example
注意:下载以下示例的gif文件
例: (Example:)
AnimationDemo.java
AnimationDemo.java
import java.awt.*;
import java.applet.*;
public class AnimationDemo extends Applet
{
Image p;
public void init()
{
p = getImage(getDocumentBase(),"ball.gif");
}
public void paint(Graphics g)
{
for(inti=0;i<500;i++)
{
g.drawImage(p, i,50, this);
try
{
Thread.sleep(100);
}
catch(Exception e)
{}
}
}
}
AnimationDemo.html
AnimationDemo.html
JApplet类 (JApplet class)
In Java, JApplet is the public class of swing. JApplet extends the class in java.applet.Applet. JApplet generates a bytecode with the help of JVM or the Applet viewer. JApplet can be written in any programming language and then can be compiled for Java Byte code.
在Java中,JApplet是swing的公共类。 JApplet扩展了java.applet.Applet中的类。 JApplet在JVM或Applet查看器的帮助下生成字节码。 JApplet可以用任何编程语言编写,然后可以针对Java Byte代码进行编译。
例: (Example:)
JAppletDemo.java
JAppletDemo.java
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class JAppletDemo extends JApplet implements ActionListener
{
JButton b;
JTextField t;
public void init()
{
t=new JTextField();
t.setBounds(30,40,220,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);
add(t);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e)
{
t.setText("Welcome to studytonight.com");
}
}
JAppletDemo.html
JAppletDemo.html
小程序中的绘画 (Painting in Applet)
Below is an example of Painting using mouseDragged() method of MouseMotionListener in Applet.
下面是使用Applet中的MouseMotionListener的mouseDragged()方法绘画的示例。
例: (Example:)
PaintingDemo.java
PaintingDemo.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class PaintingDemo extends Applet implements MouseMotionListener
{
public void init()
{
addMouseMotionListener(this);
setBackground(Color.white);
}
public void mouseDragged(MouseEvent me)
{
Graphics g=getGraphics();
g.setColor(Color.black);
g.fillOval(me.getX(),me.getY(),5,5);
}
public void mouseMoved(MouseEvent me)
{}
}
PaintingDemo.html
PaintingDemo.html
Applet中的模拟时钟 (Analog Clock in Applet)
In java, Applet can be used for creating anAnalog Clock. For creating a program for the Analog clock, java.apple, java.awt, java.util, and java.text package are imported. Date and Time functions are also used. Math functions play an important role in creating an Analog Clock. below is a program for creating anAnalog Clock.
在Java中,Applet可用于创建模拟时钟。 为了创建用于模拟时钟的程序,需要导入java.apple,java.awt,java.util和java.text包。 还使用日期和时间功能。 数学函数在创建模拟时钟中起着重要作用。 以下是用于创建模拟时钟的程序。
例: (Example:)
AnalogDemo1.java
AnalogDemo1.java
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;
public class AnalogDemo1 extends Applet implements Runnable
{
int width, height;
Thread t = null;
booleanthreadSuspended;
int hours=0, minutes=0, seconds=0;
String timeString = "";
public void init()
{
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}
public void start()
{
if ( t == null )
{
t = new Thread( this );
t.setPriority( Thread.MIN_PRIORITY );
threadSuspended = false;
t.start();
}
else
{
if ( threadSuspended )
{
threadSuspended = false;
synchronized( this )
{
notify();
}
}
}
}
public void stop()
{
threadSuspended = true;
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours> 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );
SimpleDateFormat formatter = new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );
Date date = cal.getTime();
timeString = formatter.format( date );
if ( threadSuspended ) {
synchronized( this ) {
while ( threadSuspended ) {
wait();
}
}
}
repaint();
t.sleep( 1000 );
}
}
catch (Exception e) { }
}
void drawHand( double angle, int radius, Graphics g ) {
angle -= 0.5 * Math.PI;
int x = (int)( radius*Math.cos(angle) );
int y = (int)( radius*Math.sin(angle) );
g.drawLine( width/2, height/2, width/2 + x, height/2 + y );
}
void drawWedge( double angle, int radius, Graphics g ) {
angle -= 0.5 * Math.PI;
int x = (int)( radius*Math.cos(angle) );
int y = (int)( radius*Math.sin(angle) );
angle += 2*Math.PI/3;
int x2 = (int)( 5*Math.cos(angle) );
int y2 = (int)( 5*Math.sin(angle) );
angle += 2*Math.PI/3;
int x3 = (int)( 5*Math.cos(angle) );
int y3 = (int)( 5*Math.sin(angle) );
g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y );
g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y );
g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );
}
public void paint( Graphics g ) {
g.setColor( Color.pink );
drawWedge( 2*Math.PI * hours / 12, width/5, g );
drawWedge( 2*Math.PI * minutes / 60, width/3, g );
drawHand( 2*Math.PI * seconds / 60, width/2, g );
g.setColor( Color.white );
g.drawString( timeString, 10, height-10 );
}
}
AnalogueDemo1.html
AnalogueDemo1.html
小程序中的数字时钟 (Digital Clock in Applet)
In java, Applet can be used for creating a Digital Clock. For creating a program for the digital clock, java.apple, java.awt, java.util, and java.text package are imported. Date and Time functions are also used. below is a program for creating a Digital Clock.
在Java中,Applet可用于创建数字时钟。 为了创建用于数字时钟的程序,需要导入java.apple,java.awt,java.util和java.text包。 还使用日期和时间功能。 下面是创建数字时钟的程序。
例: (Example:)
DigitalClockDemo1.java
DigitalClockDemo1.java
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;
public class DigitalClockDemo1 extends Applet implements Runnable
{
Thread t = null;
int h=0, m=0, s=0;
String timeString = "";
public void init()
{
setBackground( Color.black);
}
public void start()
{
t = new Thread( this );
t.start();
}
public void run()
{
try
{
while (true)
{
Calendar cal = Calendar.getInstance();
h = cal.get( Calendar.HOUR_OF_DAY );
if ( h> 12 ) h -= 12;
m = cal.get( Calendar.MINUTE );
s = cal.get( Calendar.SECOND );
SimpleDateFormat f = new SimpleDateFormat("hh:mm:ss");
Date date = cal.getTime();
timeString = f.format( date );
repaint();
t.sleep( 1000 );
}
}
catch (Exception e) { }
}
public void paint( Graphics g )
{
g.setColor( Color.white );
g.drawString( timeString, 50, 50 );
}
}
DigitalClockDemo1.html
DigitalClockDemo1.html
翻译自: https://www.studytonight.com/java/java-applet.php
java小程序