Graphics实现简易画图板
点击按钮选择图形和颜色,使用鼠标在界面上绘制绘制。
实现思路
UI
- 使用JFrame创建窗口,设置大小和标题。
- 添加JButton,分为图形选择按钮和颜色选择按钮。
监听
- 新建一个DrawListener类实现ActionListener和MouseListener接口
- 重写ActionListener的actionPerformed方法,为按钮添加监听addActionListener
- 重写MouseListener的mousePressed和mouseReleased方法,为界面添加鼠标监听addMouseListener
- 事件对象封装了事件的信息,包括时间、事件源对象 、事件命令、id等
Graphics绘图
- Graphics用于处理屏幕上的图形渲染
- 除了可以绘制线段,矩形,圆等基本图形,还可以绘制更为复杂的图形和字符串,本篇仅绘制了线段、矩形和圆
- JFrame对象包含一个Graphics对象,在绘制时需要获取JFrame的Graphics对象g,通过g来绘制
效果
完整代码
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class DrawListener implements ActionListener, MouseListener {
private int x1,x2,y1,y2;
private String name;
private Color color;
public Graphics g;
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("")){
//点击颜色按钮
JButton jButton = (JButton)e.getSource();
co