下面我将分享用Java制作简易画图板的过程。
version 1
Draw.java
Java代码
importjavax.swing.JFrame;
/**
*
* @author yangzhenlin
*
*/
publicclassDrawextendsJFrame {
publicvoidinitDraw() {
this.setTitle("画图板");
this.setSize(600,500);
this.setDefaultCloseOperation(3);
this.setVisible(true);
/**
* 从窗体上获取画布对象 获取窗体在屏幕上占据的区域,这块区域是允许改变颜色的。
*/
java.awt.Graphics g =this.getGraphics();
DrawListener dlis =newDrawListener(g);
this.addMouseListener(dlis);
}
}
import javax.swing.JFrame;
/**
*
* @author yangzhenlin
*
*/
public class Draw extends JFrame {
public void initDraw() {
this.setTitle("画图板");
this.setSize(600, 500);
this.setDefaultCloseOperation(3);
this.setVisible(true);
/**
* 从窗体上获取画布对象 获取窗体在屏幕上占据的区域,这块区域是允许改变颜色的。
*/
java.awt.Graphics g = this.getGraphics();
DrawListener dlis = new DrawListener(g);
this.addMouseListener(dlis);
}
}
DrawListener.java
Java代码
importjava.awt.event.MouseEvent;
/**
*
* @author yangzhenlin
*
*/
/**
* 画板监听器,实现鼠标监听器接口
*/
publicclassDrawListenerimplementsjava.awt.event.MouseListener {
// private int x1, x2, y1, y2;
privatejava.awt.Graphics g;
publicDrawListener(java.awt.Graphics g) {
this.g = g;
}
publicvoidmouseClicked(MouseEvent e) {
System.out.println("mouseClicked");
}
publicvoidmousePressed(MouseEvent e) {
System.out.println("mousePressed");
}
publicvoidmouseReleased(MouseEvent e) {
System.out.println("mouseReleased");
}
publicvoidmouseEntered(MouseEvent e) {
System.out.println("mouseEntered");
}
publicvoidmouseExited(MouseEvent e) {
System.out.println("mouseExited");
}
}