绘制直线思路
- 鼠标按下时确定第一个坐标,松开时确定第二个坐标,两个坐标画一条直线。
- 通过监听器接口:鼠标监听器 监听对象
- 重要界面画布:Graphics
代码实现
创建绘图界面(DrawUI.java)
import javax.swing.*;
import java.awt.*;
public class DrawUI{
public void showUI(){
JFrame jf = new JFrame ();
jf.setTitle ("绘制图形");
jf.setSize (600,600);
jf.setDefaultCloseOperation (WindowConstants.EXIT_ON_CLOSE);
jf.setVisible (true);
Graphics g = jf.getGraphics ();
DrawListen drawlisten = new DrawListen(g);
jf.addMouseListener(drawlisten);
}
public static void main(String[] args){
DrawUI drawUI = new DrawUI ();
drawUI.showUI ();
}
}
鼠标监听器绑定(DrawListen.java)
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.ImageObserver;
import java.text.AttributedCharacterIterator;
public class DrawListen implements MouseListener {
private Graphics g;
public DrawListen(Graphics g) {
this.g = g;
}
public void mouseClicked(MouseEvent e) {
int x=e.getX();
int y=e.getY();
System.out.println("点击坐标:"+"("+x+","+y+")");
}
int x1,y1,x2,y2;
@Override
public void mousePressed(MouseEvent e) {
x1=e.getX();
y1=e.getY();
System.out.println("按压坐标:"+"("+x1+","+y1+")");
}
@Override
public void mouseReleased(MouseEvent e) {
x2=e.getX();
y2=e.getY();
System.out.println("松开坐标:"+"("+x2+","+y2+")");
g.drawLine(x1,y1,x2,y2);
}
@Override
public void mouseEntered(MouseEvent e) {
int x=e.getX();
int y=e.getY();
System.out.println("进入坐标:"+"("+x+","+y+")");
}
@Override
public void mouseExited(MouseEvent e) {
int x=e.getX();
int y=e.getY();
System.out.println("离开坐标:"+"("+x+","+y+")");
}
}