一个小画图程序有点疑惑~
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class ad extends Applet implements ActionListener
{
Button b1=new Button( "画圆 ");
Button b2=new Button( "画矩形 ");
Graphics g;
public void init()
{
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
g.setColor(Color.BLUE);
g.drawRect(50,50,20,20);
}
else if(e.getSource()==b2)
{
g.setColor(Color.green);
g.drawOval(100,100,30,30);
}
}
}
这样嵌入网页里面后运行会报错,我想知道方法上是不是有错误。。
这个程序就是按一个按钮就画矩形或者画圆形..
谢谢求解..
------解决方案--------------------给你改了一点:
import java.applet.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
public class ad extends Applet implements ActionListener
{
Button b1=new Button( "round ");
Button b2=new Button( "rect ");
Shape aShape;
Color aColor;
public void init()
{
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
if (aShape != null) {
g2d.setPaint(aColor);
g2d.draw(aShape);
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
aColor = Color.green;
aShape = new Ellipse2D.Double(100,100,30,30);
repaint();
}
else if(e.getSource()==b2)
{
aColor = Color.BLUE;
aShape = new Rectangle2D.Double(50,50,20,20);
repaint();
}
}
}