package zikao;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class BufferedImageDemo {
/*
位图使用步骤:
1,创建Image的子类对象BufferedImage(int width,int height,int ImageType),创建时需要指定位图的
宽高及类型属性,此时相当于在内存中生成了一张图片
2,调用BufferedImage对象的getGraphics()方法获取画笔,此时就可以往内存中的这张图片绘图.
3,调用paint方法中提供的Graphics对象的drawImage()方法,一次性的内存中的图片绘制到特定的组件上
好处:
实现位图的缓冲区,用户体验优化
*/
private final Frame frame = new Frame("简单手绘程序");
private final int AREA_WIDTH = 500;
private final int AREA_HEIGHT = 400;
//定义一个右键菜单,设置画笔颜色
private final PopupMenu colorMenu = new PopupMenu();
private final MenuItem redItem = new MenuItem("红色");
private final MenuItem greenItem = new MenuItem("绿色");
private final MenuItem blueItem = new MenuItem("蓝色");
//定义一个记录画笔颜色的变量
private Color forceColor = Color.BLACK;
//创建一个BufferedImage位图对象
private int preX = -1;
private int preY = -1;
BufferedImage image = new BufferedImage(AREA_WIDTH, AREA_HEIGHT, BufferedImage.TYPE_INT_RGB);
//通过位图,获取关联的Graphics对象
Graphics g = image.getGraphics();
private class MyCanvas extends Canvas {
@Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
}
}
MyCanvas drawArea = new MyCanvas();
public void init() {
ActionListener listener = e -> {
String actionCommand = e.getActionCommand();
switch (actionCommand) {
case "红色" -> forceColor = Color.RED;
case "绿色" -> forceColor = Color.GREEN;
case "蓝色" -> forceColor = Color.BLUE;
}
};
redItem.addActionListener(listener);
greenItem.addActionListener(listener);
blueItem.addActionListener(listener);
colorMenu.add(redItem);
colorMenu.add(greenItem);
colorMenu.add(blueItem);
drawArea.add(colorMenu);
drawArea.addMouseListener(new MouseAdapter() {
@Override
//鼠标键抬起
public void mouseReleased(MouseEvent e) {
boolean popupTrigger = e.isPopupTrigger();
if (popupTrigger) {
colorMenu.show(drawArea, e.getX(), e.getY());
}
//重置preX和preY
preY = -1;
preX = -1;
}
});
//设置位图的背景颜色为白色
g.setColor(Color.white);
g.fillRect(0, 0, AREA_WIDTH, AREA_HEIGHT);
//通过监听鼠标移动,完成线条绘制
drawArea.addMouseMotionListener(new MouseAdapter() {
//该方法当鼠标左键按下,并进行拖动时触发
@Override
public void mouseDragged(MouseEvent e) {
if (preX > 0 && preY > 0) {
g.setColor(forceColor);
g.drawLine(preX, preY, e.getX(), e.getY());
}
//修正preX和preY的值
preY = e.getY();
preX = e.getX();
//重绘组件
drawArea.repaint();
}
}
);
drawArea.setPreferredSize(new Dimension(AREA_WIDTH, AREA_HEIGHT));
frame.add(drawArea);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new BufferedImageDemo().init();
}
}
Java Awt 实现绘画版效果
最新推荐文章于 2022-10-08 15:35:37 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)