很有趣的APPLET小程序
今天早上在java教材上修改运行了一个很简单的Applet小程序,原题是通过移动鼠标来绘制圆圈,稍微修改了一下便可以产生彩色的圆圈。很不错,还可以选择不同的图形,例如矩形、圆之类的,但是有一个缺陷,将窗口放大后,那个按钮是看不见的,必须将鼠标移动到按钮处才会有按钮显示,一共有五个按钮,都处于窗口上方。
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class TestDemo extends Applet implements MouseMotionListener{
private static final long serialVersionUID = 1L;
private Color[] core ={Color.black,Color.blue,Color.cyan,Color.DARK_GRAY,
Color.green,Color.lightGray,Color.orange,Color.pink};
protected static int taskcounts=0;
private static int taskid=0;
int x,y;
JPanel panel= new JPanel();
JButton item = new JButton("实心圆");
JButton item1 = new JButton("空心圆");
JButton item2 = new JButton("空心矩形");
JButton item3 = new JButton("实心矩形");
JButton item4 = new JButton("画线");
public void init(){
this.addMouseMotionListener(this);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
taskid=1;
}
});
item1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
taskid=2;
}
});
item2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
taskid=3;
}
});
item3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
taskid=4;
}
});
item4.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
taskid=5;
}
});
}
public void start(){
add(panel);
panel.add(item); panel.add(item1);
panel.add(item2); panel.add(item3);
panel.add(item4);
setVisible(true);
}
public void paint(Graphics g){
setVisible(true);
if(taskcounts==8)taskcounts=0;
g.setColor(core[taskcounts++]);
switch(taskid){
case 0:
case 1:g.fillOval(x, y, 30, 30);break;
case 2:g.drawOval(x, y, 30, 30);break;
case 3:g.drawRect(x, y, 50, 50);break;
case 4:g.fillRect(x, y, 50, 50);break;
case 5:g.fillOval(x, y, 1, 1);break;
}
repaint();
}
public void update(Graphics g){
paint(g);setVisible(true);
}
public void mouseDragged(MouseEvent e) {
x=e.getX();y=e.getY();
}
public void mouseMoved(MouseEvent e) {
}
}
运行之后就能看到效果,蛮好看的