点击按钮选择图形和颜色,使用鼠标在界面上绘制绘制。
实现思路 UI- 使用Jframe创建窗口,设置大小和标题。
- 添加JButton,分为图形选择按钮和颜色选择按钮。
- 新建一个DrawListener类实现ActionListener和MouseListener接口
- 重写ActionListener的actionPerformed方法,为按钮添加监听addActionListener
- 重写MouseListener的mousePressed和mouseReleased方法,为界面添加鼠标监听addMouseListener
- 事件对象封装了事件的信息,包括时间、事件源对象 、事件命令、id等
- 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();
color = jButton.getBackground();
g.setColor(color);
}else {
//点击图形按钮
name = command;
}
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
x1 = e.getX();
y1 = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
int w = x2-x1;
int h = y2-y1;
//绘制图形
if (name.equals("直线")){
g.drawLine(x1,y1,x2,y2);
}else if (name.equals("矩形")){
g.drawRect(Math.min(x1,x2),Math.min(y1,y2),Math.abs(w),Math.abs(h));
}else if (name.equals("圆")){
g.drawOval(Math.min(x1,x2),Math.min(y1,y2),Math.abs(w),Math.abs(h));
}else if (name.equals("实心圆")){
g.fillOval(Math.min(x1,x2),Math.min(y1,y2),Math.abs(w),Math.abs(h));
}
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
import javax.swing.*;
import java.awt.*;
public class DrawTest {
//可绘制的图形
private String[] strs = {"直线","矩形","圆","实心圆"};
//可选颜色
private Color[] colors = {
Color.BLACK,
Color.LIGHT_GRAY,
Color.GRAY,
Color.WHITE,
Color.YELLOW,
Color.RED,
Color.GREEN,
Color.BLUE
};
public void show(){
Jframe jf = new Jframe("图形绘制");
jf.setSize(1000,1000);
jf.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);
FlowLayout fl = new FlowLayout();
jf.setLayout(fl);
//设置监听
DrawListener drawListener = new DrawListener();
//设置大小
Dimension dm = new Dimension(75,50);
for (int i = 0; i < strs.length; i++) {
JButton jButton = new JButton(strs[i]);
jButton.setPreferredSize(dm);
jButton.addActionListener(drawListener);
jf.add(jButton);
}
for (int i = 0; i < colors.length; i++) {
JButton jButton = new JButton();
jButton.setBackground(colors[i]);
jButton.setPreferredSize(dm);
jButton.addActionListener(drawListener);
jf.add(jButton);
}
jf.setVisible(true);
//向drawListener中传入g必须在setVisible之后
Graphics g = jf.getGraphics();
drawListener.g = g;
jf.addMouseListener(drawListener);
}
public static void main(String[] args) {
new DrawTest().show();
}
}



