1. 程式人生 > >繪圖小程序

繪圖小程序

nbsp 一次 reset div gen 面板 public ner main

點擊鼠標左鍵時,可以進行繪圖操作,當點擊鼠標右鍵時,清空屏幕。

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class MouseEventDemo extends JFrame{
    
private JPanel p; //鼠標上一次的坐標 int pre_x = -1,pre_y = -1; //鼠標當前坐標 int x, y; public MouseEventDemo(){ super("畫板"); p=new JPanel(); //註冊鼠標監聽 p.addMouseMotionListener(new PaintListener()); p.addMouseListener(new ResetListener()); //將面板添加到窗體中 this
.add(p); //設定窗口大小 this.setSize(400,300); //設定窗口左上角坐標 this.setLocation(200, 100); //設定窗口默認關閉方式為退出應用程序 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //設置窗口可見 this.setVisible(true); } //重寫JFrame的paint()方法,此方法用於在窗體中畫圖 public void paint(Graphics g){
//設置畫筆顏色 g.setColor(Color.red); //歷史坐標>0 if(pre_x>0&&pre_y>0){ //繪制一條線段,從上一次鼠標拖動事件點到本次鼠標拖動事件點 g.drawLine( pre_x, pre_y, x, y); } //保存當前鼠標坐標,稱為上一次的歷史坐標 pre_x=x; pre_y=y; } //定義鼠標拖動監聽類 class PaintListener implements MouseMotionListener{ //鼠標移動的處理方法 public void mouseMoved(MouseEvent e){ } //鼠標拖動的處理方法,負責畫畫工作 public void mouseDragged(MouseEvent e){ //獲得鼠標當前坐標 x=e.getX(); y=e.getY(); //重畫,reprint()觸發paint() MouseEventDemo.this.repaint(); } } //定義鼠標監聽類 class ResetListener implements MouseListener{ //鼠標單擊事件處理 public void mouseClicked(MouseEvent e){ } //鼠標按下事件處理 public void mousePressed(MouseEvent e){ //獲取鼠標按鍵,判斷是否為右鍵 if(e.getButton()==MouseEvent.BUTTON3){ //重畫面板(擦除原來的軌跡) MouseEventDemo.this.p.repaint(); } } //鼠標松開事件處理,重置歷史坐標 public void mouseReleased(MouseEvent e){ //鼠標松開時,將歷史坐標設置為-1(重置) pre_x=-1; pre_y=-1; } //鼠標進入事件處理 public void mouseEntered(MouseEvent e){ } //鼠標退出事件處理 public void mouseExited(MouseEvent e){ } } public static void main(String[] args) { // TODO Auto-generated method stub new MouseEventDemo(); } }

繪圖小程序