使用鼠标在窗体上绘制图形
界面开发:只需要一个窗体
监听器:
- 鼠标监听器:MouseListener 监听鼠标在窗体上的操作
- 鼠标事件参数:MouseEvent获取鼠标操作时的参数 数据(坐标)
Graphics(图形渲染工具):
屏幕上的内容都是GPU经过对每个像素点需要显示的颜色进行排列 然后控制屏幕显示出来
- 从窗体对象上获取,在窗体上绘制 Graphics g=jf.getGraphics();
- 必须在可视化之后获取
- 需要在鼠标操作后使用
- 绘制直线:g.drawLine(x1,y1,x2,y2);
package tky1024;
import javax.swing.*;
import java.awt.*;
public class Drawpad {
public void showUI(){
JFrame jf=new JFrame();
jf.setTitle("画图板");
jf.setSize(700,800);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
DrawListener drawListener=new DrawListener();
jf.addMouseListener(drawListener);
Graphics g=jf.getGraphics();
drawListener.g=g;
}
public static void main(String[] args) {
Drawpad drawpad=new Drawpad();
drawpad.showUI();
}
}
package tky1024;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class DrawListener implements MouseListener {
Graphics g;
int x1,y1,x2,y2;
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("点击");
int x= e.getX();
int y=e.getY();
System.out.println("x="+x+" y="+y);
}
@Override
public void mousePressed(MouseEvent e) {
System.out.println("按下");
int x= e.getX();
int y=e.getY();
System.out.println("x="+x+" y="+y);
x1=x;
y1=y;
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("松开");
int x= e.getX();
int y=e.getY();
System.out.println("x="+x+" y="+y);
x2=x;
y2=y;
g.drawLine(x1,y1,x2,y2);
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}