java applet 一个简单的例子(applet+html)
java applet是一个类,其层次结构如下图:
类 JApplet
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
javax.swing.JApplet
编译applet:
类 JApplet
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
javax.swing.JApplet
编写applet类,继承Applet或是JApplet,然后完成init方法,在创建一个加载applet的html页面
- package ch10;
- /**
- @version 1.21 2004-05-07
- @author Cay Horstmann
- */
- /*
- The following HTML tags are required to display this applet in a browser:
- <applet code="NotHelloWorldApplet.class" width="300" height="100">
- </applet>
- */
- import javax.swing.*;
- public class NotHelloWorldApplet extends JApplet
- {
- public void init()
- {
- JLabel label = new JLabel("Not a Hello, World applet", SwingConstants.CENTER);
- add(label);
- }
- }
- <applet code="ch10.NotHelloWorldApplet.class"
- width="300" height="100">
- </applet>
编译applet:
javac NotHelloWorldApplet.Java
而后用applet查看器appletviewer查看html:
appletviewer NotHelloWorldApplet.class
或者是直接打开html文件(需浏览器支持JAVA(TM)插件)。
编写一个Applet,在途中加入标签“旋转角度”和文本框,安排两个按钮“顺时针旋转”和“逆时针旋转”,在文本框中填写旋转角度,通过按钮实现旋转.
- import java.applet.*;
- import java.awt.*;
- import java.awt.event.*;
- import java.awt.geom.*;
- public class g2DRotate2 extends Applet implements ActionListener{
- Label label;
- TextField angle;
- Button b1,b2;
- int flag=1;
- public void init(){
- setLayout(null);
- label=new Label("旋转角度:");
- label.setBounds(250,100,65,20);
- angle=new TextField("0.0",10);
- angle.setBounds(330,100,65,20);
- b1=new Button("顺时针旋转");
- b2=new Button("逆时针旋转");
- b1.setBounds(250,130,65,20);
- b2.setBounds(330,130,65,20);
- b1.addActionListener(this);
- b2.addActionListener(this);
- add(label);
- add(angle);
- add(b1);
- add(b2);
- show();
- }
- public void paint(Graphics g){
- int x=130,y=100;
- int i=0;
- Graphics2D g2=(Graphics2D)g;
- g.setColor(Color.blue);
- g2.draw(new Ellipse2D.Double(x,y,20,90));
- g.setColor(Color.black);
- g.drawRect(x,y,20,90);
- g2.translate(150,100);//平移到(150,100),作为下面旋转的起点
- if(flag==1)
- g2.rotate(Double.parseDouble(angle.getText()));//将角度转换成弧度
- else
- g2.rotate(-Double.parseDouble(angle.getText()));
- g.setColor(Color.blue);
- g2.draw(new Ellipse2D.Double(-20,0,20,90));
- g.setColor(Color.black);
- g.drawRect(-20,0,20,90);
- }
- public void actionPerformed(ActionEvent e) {
- if(e.getSource()==b1){
- flag=1;
- repaint();
- }else{
- flag=-1;
- repaint();
- }
- }
- }
个人在360浏览器调试成功
转自:http://blog.csdn.net/caomiao2006/article/details/17536187
code下载
http://pan.baidu.com/s/1kU5miUj