如何用Java编写一个绘制图形的小程序?

如何用Java编写一个绘制图形的小程序?,第1张

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()//重绘组件

}

}

}

import java.applet.*

import java.awt.*

import java.awt.event.*

public class Tester extends Applet implements ActionListener

{

Button btn1,btn2,btn3,btn4

public void init(){

setLayout(null)

btn1=new Button("歼滚绘制直氏孝余线")

btn2=new Button("绘制矩形")

btn3=new Button("慎裂绘制圆")

add(btn1)

add(btn2)

add(btn3)

btn1.setBounds(10, 60, 60, 20)

btn2.setBounds(10, 90, 60, 20)

btn3.setBounds(10, 120, 60, 20)

btn1.addActionListener(this)

btn2.addActionListener(this)

btn3.addActionListener(this)

validate()

setVisible(true)

}

public void start(){

}

public void actionPerformed(ActionEvent e)

{

Graphics g=this.getGraphics()

if(e.getSource()==btn1)

{

g.drawLine(200, 100, 300, 200)

}

else if(e.getSource()==btn2)

{

g.drawRect(200, 250, 200, 200)

}

else

{

g.drawArc(200, 500, 200, 200, 0, 360)

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/yw/12319169.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-22
下一篇2023-05-22

发表评论

登录后才能评论

评论列表(0条)

    保存