當前位置:編程學習大全網 - 編程軟體 - 如何用Java編寫壹個繪制圖形的小程序?

如何用Java編寫壹個繪制圖形的小程序?

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(); //重繪組件

}

}

}

  • 上一篇:別克英朗車載音響低音怎麽調大?
  • 下一篇:毛衣手工編織教程
  • copyright 2024編程學習大全網