程序说明:
1. 使用Graphic类在Canvas上绘制直线,使用MouseListener、MouseMotionListener 进行事件监听。
2. 共两个文件 PaintLineCanvas.java、Main.java。如下:
程序代码:
package top.ryanlv.draw;
/**
* PaintLineCanvas.java 实现“画板”功能
*/
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class PaintLineCanvas extends Canvas implements MouseListener, MouseMotionListener{
private Point start, end, lastend;
public PaintLineCanvas() {
start = null;
end = null;
lastend = null;
this.addMouseListener(this); //增加鼠标监听
this.addMouseMotionListener(this); //增加鼠标移动监听
}
//-->鼠标移动监听:鼠标拖动、鼠标移动
@Override
public void mouseDragged(MouseEvent e) {
lastend = end;
end = new Point(e.getX(), e.getY());
this.repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
//<--鼠标移动监听
//-->鼠标监听:单击、按下、放开、进入、离开
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
start = new Point(e.getX(), e.getY()); //record the beginning point
}
@Override
public void mouseReleased(MouseEvent e) {
end = new Point(e.getX(), e.getY()); //record the ending point
this.repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
//<--鼠标监听
public void paint(Graphics g) {
if(start!=null && lastend!=null) {
g.setColor(this.getBackground());
g.drawLine(start.x, start.y, lastend.x, lastend.y);
g.setColor(Color.blue);
g.drawLine(start.x, start.y, end.x, end.y);
}
}
public void update(Graphics g) {
print(g);
}
}
package top.ryanlv.draw;
/**
* 初始化顶层窗口 JFrame, 运行程序;
*/
import javax.swing.JFrame;
public class Main extends JFrame{
public Main() {
//初始化:继承父类、设置大小、位置、关闭方式、添加组件、设置为可见。
super("画图");
this.setSize(400, 400);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.getContentPane().add(new PaintLineCanvas());
this.setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}