import java.awt.*
import java.awt.event.*
import java.awt.geom.*
import javax.swing.*
//不规则图形的绘制
public class IrregularShapeDemo extends JFrame {
GeneralPath gPath= new GeneralPath()//GeneralPath对象实例
Point aPoint
//构造函数
public IrregularShapeDemo() {
super("不规则图形的绘戚拦纤衡余制")//调用父类构造函数
enableEvents(AWTEvent.MOUSE_EVENT_MASK|AWTEvent.MOUSE_MOTION_EVENT_MASK)//允许事件
setSize(300, 200)//设置窗口尺寸
setVisible(true)//设置窗口可视
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)//关闭窗口时退出程序
}
public void paint(Graphics g) { //重载窗口组件的paint()方法
Graphics2D g2D = (Graphics2D)g//获取图形环境
g2D.draw(gPath)//绘制路径
}
public static void main(String[] args) {
new IrregularShapeDemo()
}
protected void processMouseEvent(MouseEvent e) { //鼠标事件处理
if(e.getID() == MouseEvent.MOUSE_PRESSED) {
aPoint = e.getPoint()//得到当前鼠标点
gPath = new GeneralPath()//重新实例化GeneralPath对象
gPath.moveTo(aPoint.x,aPoint.y)//设置路径点
}
}
protected void processMouseMotionEvent(MouseEvent e) { //鼠标运动事件处理
if(e.getID() == MouseEvent.MOUSE_DRAGGED) {
aPoint = e.getPoint()//得到当前鼠标点
gPath.lineTo(aPoint.x, aPoint.y)//设高仿置路径
gPath.moveTo(aPoint.x, aPoint.y)
repaint()//重绘组件
}
}
}
Applet小程序是需要嵌入在网页中执行的,如果你不坦腔键想用html,那圆拍么要加入public void init() {}方法,在里边初始化容器和让巧组件,那么在调用paint的时候就能看到效果了。
public class DrawLine extends Applet implements ActionListener {
Button btn
public void init() {
btn = new Button("确定")
add(btn)
btn.addActionListener(this)
}
public void paint(Graphics g) {
g.drawLine(0, 0, 500, 500)
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn) {
repaint()
}
}
}
import java.awt.*import java.awt.event.*
import java.util.*
import javax.swing.*
class MyLine
{
private int x1,x2,y1,y2
public MyLine(int x1,int x2,int y1,int y2)
{
this.x1=x1
this.x2=x2
this.y1=y1
this.y2=y2
}
public void drawMe(Graphics g)
{
g.drawLine(x1,y1,x2,y2)
g.drawString("起始坐标:"+new String(x1+","+y1),x1,y1)
}
}
public class DrawLine extends Frame
{
Vector v=new Vector()
public static void main(String[]args)
{
DrawLine dl=new DrawLine()
dl.init()
}
public void paint(Graphics g)
{
g.setColor(Color.BLUE)
Enumeration en=v.elements()
while(en.hasMoreElements())
{
MyLine m=(MyLine)en.nextElement()
m.drawMe(g)
}
}
public void init()
{
setSize(300,300)
setVisible(true)
addMouseListener(new MouseAdapter()
{
int x1,x2,y1,y2
public void mousePressed(MouseEvent e)
{
x1=e.getX()
y1=e.getY()
}
public void mouseReleased(MouseEvent e)
{
x2=e.getX()
y2=e.getY()
Graphics g=e.getComponent().getGraphics()
g.setColor(Color.BLUE)
g.drawLine(x1,y1,x2,y2)
g.drawString(new String("起始点坐档答冲标:"+x1+"举念,"行歼+y1),x1,y1)
v.add(new MyLine(x1,x2,y1,y2))// here pay attention
}
})
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
((Window)e.getSource()).dispose()
System.exit(0)
}}
)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)