用Java做一个涂鸦板
百度广告
首先,创建项目和包。并创建类DrawLine。继承java.awt.Frame类
需要定义几个变量来定义画图的起点坐标(X,Y)和终点。drawing定义是否要画图的判断变量。
然后添加鼠标事件监听器(MouseListener和MouseMotionListener)只需要再三个鼠标事件中实现方法,即按下鼠标,拖动鼠标,抬起鼠标。
重写pain()方法,调用画线的方法drawLine(startX,startY,endX,endY)在Frame中绘制。只有这个方法还不行,因为我们需要完整的不断的显示在Frame中,所以还要重写update()方法一边更新Frame中的Graphics。
这样,一个涂鸦面板就做好了。
代码
package com.godtzsd.cn;
import java.awt.*;
import java.awt.event.*;
import java.util.EventListener;
import java.awt.event.MouseMotionListener;
public class DrawLine extends Frame implements MouseListener,MouseMotionListener {
int startX,startY; //定义画图的起点X和Y的坐标
int endX,endY; //定义画图的终点X和Y的坐标
boolean drawing=false;
public DrawLine() {
// TODO Auto-generated constructor stub
super("涂鸦面板");
this.addMouseListener(this);
this.addMouseMotionListener(this);
this.addWindowListener(new WindowListener(){
public void windowActivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub
}
public void windowClosing(WindowEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
public void windowIconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub
}
});
this.setSize(180,160);
this.setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
g.drawLine(startX, startY, endX,endY);
}
public void update(Graphics g){
this.paint(g);
}
/**
* @param args
*/
public static void main(String args) {
// TODO Auto-generated method stub
new DrawLine();
}
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
this.drawing=true;
this.startX=e.getX();
this.startY=e.getY();
}
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
this.drawing=false;
}
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
if(drawing){
this.endX=e.getX();
this.endY=e.getY();
this.startX=e.getX(); //当前点作为起始点
this.startY=e.getY();
this.repaint();
}
}
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
编辑推荐:
温馨提示:因考试政策、内容不断变化与调整,长理培训网站提供的以上信息仅供参考,如有异议,请考生以权威部门公布的内容为准! (责任编辑:长理培训)
点击加载更多评论>>