用java写的简易画图板(可以用作对图片签名,呵呵)

来源:互联网 发布:亚洲人适合的发型 知乎 编辑:程序博客网 时间:2024/05/16 09:54

这段程序是我的一个项目里的一段,原本设计的目的是实现对图片进行个性化手写签名,实现这样的方式有很多,但是由于这个项目是全触摸屏设备使用,没有鼠标和键盘,所以就这样设计了。基本思想是将图片作为背景,然后以手写板的方式直接绘制,然后生成新的图片,呵呵!可能有点小题大作,如果大家有什么别的方式实现,欢迎留言指教,本人虚心学习中。。。

程序代码如下:

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestBackground implements MouseMotionListener,ActionListener {
 /**
  * 项目笔记
  */


 static final int r=3;
 static int ox, oy;
 static int flag=1;//颜色控制
 public static void main(String[] args) {
 JFrame f = new JFrame();
 
 JPanel panel = new JPanel() {
 
   ImageIcon  img = new ImageIcon("edit.jpg");
  public void paintComponent(Graphics g) {
   g.drawImage(img.getImage(), 0,40, this);
   super.paintComponent(g);
  }
 };

 panel.setLayout(new FlowLayout());
 
  JButton jButton1 = new JButton("红");
  JButton jButton2 = new JButton("黑");
  JButton jButton3 = new JButton("绿");
  JButton jButton4 = new JButton("保存");
  JButton jButton5 = new JButton("退出");
 
 
  panel.setOpaque(false);
  panel.add(jButton1);
  panel.add(jButton2);
  panel.add(jButton3);
  panel.add(jButton4);
  panel.add(jButton5);
 
  jButton1.addActionListener(new  TestBackground());
  jButton2.addActionListener(new  TestBackground());
  jButton3.addActionListener(new  TestBackground());
  jButton4.addActionListener(new  TestBackground());
  panel.addMouseMotionListener(new  TestBackground());
 
  f.setContentPane(panel);
  f.setSize(800, 600);
  f.setVisible(true);
 }

public void mouseDragged(MouseEvent e) {
 Container c=(Container)e.getSource();
    Graphics g=c.getGraphics();
     if (oy>=40) {
     if(flag==1){
      g.setColor(new Color(168,0,255));
      g.fillRect(ox, oy, 3, 3);}
     else if(flag==2){
      g.setColor(new Color(0,0,0));
     g.fillRect(ox, oy, 3, 3);
     }
     else{
      g.setColor(new Color(0,255,0));
       g.fillRect(ox, oy, 3, 3);
    }}
    ox=e.getX();oy=e.getY();
 
}
public void mouseMoved(MouseEvent e) {
    ox=-1;oy=-1;
 
}
public void actionPerformed(ActionEvent e) {
 if(e.getActionCommand().equals("红")){
      flag=1; }
     else if (e.getActionCommand().equals("黑")){
      flag=2;}
     else if (e.getActionCommand().equals("绿")){
      flag=3;}
     else if (e.getActionCommand().equals("退出"))
      System.exit(0);}
}