⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 gdraw.java

📁 用Java语言实现的简单的画图软件
💻 JAVA
字号:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

import java.awt.image.*;
import com.sun.image.codec.jpeg.*;
public class Gdraw extends JFrame//框架类
{
	  JMenuItem choices[];//菜单项数组
	  String names[]={"自由画","直线","矩形","实心矩形","椭圆","实心椭圆","圆","实心圆","圆角矩形",
	                  "实心圆角矩形","清除工具"};
	  String Text[]={"用铅笔随意画","画一条直线","画空心的矩形","画一个实心矩形","画一个空心椭圆","画一个实心椭圆",
	                  "画一个圆","画一个实心圆","画一个圆角矩形","画一个实心圆角矩形","清除工具"};
	  JLabel statusBar;//显示鼠标状态的提示条组件
	  DrawPanel drawingArea;//画图区域
	  drawings[]itemList=new drawings[5000];//存放基本图形的数组
	  int Choice=0;//设置默认状态
	  int index=0;//当前已经绘制的图形数目
	  ObjectOutputStream output; //定义输入输出流
	  ObjectInputStream input; //定义输入输出流
	  //用于保存为GIF文件格式
	  BufferedImage image=new BufferedImage(200,200,BufferedImage.TYPE_INT_RGB);
	  JFrame window;
	  public Gdraw()//构造函数
	  {
	   super("简单绘图");
	   JMenuBar bar=new JMenuBar();//定义菜单条
	   JMenu fileMenu=new JMenu("文件");
	  //新建文件菜单条
	   JMenuItem newItem=new JMenuItem("新建");
	   newItem.addActionListener(
	          new ActionListener(){
	                  public void actionPerformed(ActionEvent e)
	                  {
	                   newFile();//如果被单击,则调用新建文件方法
	                  }
	          }
	   );
	   fileMenu.add(newItem);
	   fileMenu.addSeparator();
	 //保存文件菜单项
	   JMenuItem saveItem1=new JMenuItem("保存");
	   saveItem1.addActionListener(
	          new ActionListener(){
	                  public void actionPerformed(ActionEvent e)
	                  {
	                   saveFile1();//如果被单击,则调用保存文件方法
	                  }
	          }
	   );
	   fileMenu.add(saveItem1);
	   fileMenu.addSeparator();
	 //保存文件菜单项
	   JMenuItem saveItem2=new JMenuItem("保存为GIF图像");
	   saveItem2.addActionListener(
	          new ActionListener(){
	                  public void actionPerformed(ActionEvent e)
	                  {
	                   saveFile2();//如果被单击,则调用保存文件方法
	                  }
	          }
	   );
	   fileMenu.add(saveItem2);
	   fileMenu.addSeparator();
	 //打开文件菜单项
	   JMenuItem loadItem=new JMenuItem("打开");
	   loadItem.setMnemonic('L');
	   loadItem.addActionListener(
	          new ActionListener(){
	                  public void actionPerformed(ActionEvent e)
	                  {
	                   loadFile();//如果被单击,则调用打开文件方法
	                  }
	          }
	   );
	   fileMenu.add(loadItem);
	   fileMenu.addSeparator();
	   //退出菜单项
	   JMenuItem exitItem=new JMenuItem("退出");
	   exitItem.addActionListener(
	          new ActionListener(){
	                  public void actionPerformed(ActionEvent e)
	                  {
	                   System.exit(0);//如果被单击,则调用退出画图板方法
	                  }
	          }
	   );
	   fileMenu.add(exitItem);
	   bar.add(fileMenu);
	   //设置绘图菜单
	   JMenu DrawMenu=new JMenu("绘图");
	   bar.add(DrawMenu);
	   //创建各种基本图形的菜单项
	    drawingArea=new DrawPanel();
	    choices=new JMenuItem[names.length];
	    JianTing JT=new JianTing();
	    for(int i=0;i<choices.length;i++)
	    {
	     choices[i]=new JMenuItem( names[i]);
	     DrawMenu.add(choices[i]);
	     if(i<choices.length-1)
	    	 DrawMenu.addSeparator();
	    }
	    //将监听器加入菜单项里面
	    for(int i=0;i<choices.length;i++)
	    {
	     choices[i].addActionListener(JT);
	    }
	    Container c=getContentPane();
	    super.setJMenuBar( bar );
	    c.add(drawingArea);
	    statusBar=new JLabel();//显示默认状态
	    c.add(statusBar,BorderLayout.SOUTH);
	    createNewItem();
	    setSize(840,550);
	    setVisible(true);
	  }
	 //监听器JianTing类,内部类,用来监听菜单项的操作
	 public class JianTing implements ActionListener
	 {
	  public void actionPerformed(ActionEvent e)
	  {
	   for(int j=0;j<choices.length;j++)
	   {
	      if(e.getSource()==choices[j])
	         {Choice=j;
	          createNewItem();
	          repaint();}
	        }
	    }
	 }
	//鼠标事件mouse1类,用来完成鼠标相应事件操作
	 class mouse1 extends  MouseAdapter
	 {
	   public void mousePressed(MouseEvent e)
	    {
	     itemList[index].x1=itemList[index].x2=e.getX();
	     itemList[index].y1=itemList[index].y2=e.getY();
	    //如果当前选择的图形是随笔画或者清除工具,则进行下面的操作
	    if(Choice==0||Choice==10)
	    {
	     itemList[index].x1=itemList[index].x2=e.getX();
	     itemList[index].y1=itemList[index].y2=e.getY();
	     index++;
	     createNewItem();
	     }
	    }
	   public void mouseReleased(MouseEvent e)
	    {
	    if(Choice==0||Choice==10)
	    {
	     itemList[index].x1=e.getX();
	     itemList[index].y1=e.getY();
	    }
	     itemList[index].x2=e.getX();
	     itemList[index].y2=e.getY();
	     repaint();
	     index++;
	     createNewItem();
	    }
	   public void mouseEntered(MouseEvent e)
	   {
	   }
	   public void mouseExited(MouseEvent e)
	   {
	   }
	 }
	//鼠标事件mouse2类,用来完成鼠标拖动和鼠标移动时的相应操作
	 class mouse2 implements MouseMotionListener
	 {
	  public void mouseDragged(MouseEvent e)
	  {

	   if(Choice==0||Choice==10)
	   {
	    itemList[index-1].x1=itemList[index].x2=itemList[index].x1=e.getX();
	    itemList[index-1].y1=itemList[index].y2=itemList[index].y1=e.getY();
	    index++;
	    createNewItem();
	   }
	   else
	    {
	     itemList[index].x2=e.getX();
	     itemList[index].y2=e.getY();
	    }
	   repaint();
	   }
	  public void mouseMoved(MouseEvent e)
	   {  
		  if((Choice<11)&&(Choice>=0))
			  statusBar.setText(Text[Choice]);}
	  }
	//面板类,用来画图
	 class DrawPanel extends JPanel
	 {
	   public DrawPanel()
	  {
	   setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
	   setBackground(Color.white);
	   addMouseListener(new mouse1());
	   addMouseMotionListener(new mouse2());
	  }
	   public void paintComponent(Graphics g)
	    {
	      super.paintComponent(g);
	      Graphics2D g2d=(Graphics2D)g;	//定义画笔
	      int j=0;
	      while (j<=index)
	      {
	        draw(g2d,itemList[j]);
	        j++;
	      }
	    }
	    void draw(Graphics2D g2d,drawings i)
	    {
	      i.draw(g2d);//将画笔传入到各个子类中,用来完成各自的绘图
	    }
	 }
	//新建一个画图基本单元对象
	 void createNewItem()
	  { 
	    drawingArea.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));//进行相应的游标设置
	    switch (Choice)
	    {
	      case 0:
	        itemList[index]=new Pencil();
	        break;
	      case 1:
	        itemList[index]=new Line();
	        break;
	      case 2:
	        itemList[index]=new Rect();
	        break;
	      case 3:
	        itemList[index]=new fillRect();
	        break;
	      case 4:
	        itemList[index]=new Oval();
	        break;
	      case 5:
	        itemList[index]=new fillOval();
	        break;
	      case 6:
	        itemList[index]=new Circle();
	        break;
	      case 7:
	        itemList[index]=new fillCircle();
	        break;
	      case 8:
	        itemList[index]=new RoundRect();
	        break;
	      case 9:
	        itemList[index]=new fillRoundRect();
	        break;
	      case 10:
	        itemList[index]=new Rubber();
	        break;
	    }
	  }
	//新建一个文件
	 public void newFile()
	 {
	  index=0;
	  Choice=0;
	  createNewItem();
	  repaint();//将有关值设置为初始状态,并且重画
	 }
	//保存图形
	 public void saveFile1()
	 {
	    JFileChooser fileChooser=new JFileChooser();
	    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
	    int result =fileChooser.showSaveDialog(this);
	    if(result==JFileChooser.CANCEL_OPTION)
	             return ;
	    File fileName=fileChooser.getSelectedFile();
	    fileName.canWrite();

	    if (fileName==null||fileName.getName().equals(""))
	    JOptionPane.showMessageDialog(fileChooser,"Invalid File Name",
	            "Invalid File Name", JOptionPane.ERROR_MESSAGE);
	    else{
	      try {
	       fileName.delete();
	       FileOutputStream fos=new FileOutputStream(fileName);

	       output=new ObjectOutputStream(fos);
	     

	       output.writeInt( index );

	       for(int i=0;i< index ;i++)
	       {
	               drawings p= itemList[ i ] ;
	        output.writeObject(p);
	        output.flush();
	               }
	      output.close();
	      fos.close();
	      }
	       catch(IOException ioe)
	       {
	         ioe.printStackTrace();
	       }
	      }
	   }
  //把图形保存为GIF文件
   public void saveFile2()
   {
	   
	   FileDialog savedialog=new FileDialog(window,"保存图型到JPG格式",FileDialog.SAVE);
       savedialog.setVisible(true);                                 
       if(savedialog.getFile()!=null) 
       {
          try{
                 String fileName=savedialog.getFile();    
                 FileOutputStream out=new FileOutputStream(fileName);
                 JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
                 JPEGEncodeParam param=encoder.getDefaultJPEGEncodeParam(image);
                 param.setQuality(1.0f,false);
                 encoder.setJPEGEncodeParam(param);                  
                  encoder.encode(image);
                  out.close();
                }
           catch(Exception EE)
           {
           } 
       }     
   }
  //打开文件
  public void loadFile()
  {
   JFileChooser fileChooser=new JFileChooser();
   fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
   int result =fileChooser.showOpenDialog(this);
   if(result==JFileChooser.CANCEL_OPTION)
         return ;
   File fileName=fileChooser.getSelectedFile();
   fileName.canRead();
   if (fileName==null||fileName.getName().equals(""))
      JOptionPane.showMessageDialog(fileChooser,"Invalid File Name",
           "Invalid File Name", JOptionPane.ERROR_MESSAGE);
   else 
   {
	   try
       {
		   FileInputStream fis=new FileInputStream(fileName);
           input=new ObjectInputStream(fis);
           drawings inputRecord;
           int countNumber=0;
           countNumber=input.readInt();
           for(index=0;index< countNumber ;index++)
           {
           inputRecord=(drawings)input.readObject();
           itemList[ index ] = inputRecord ;
           }
           createNewItem();
           input.close();
           repaint();
       }
       catch(EOFException endofFileException)
       {
           JOptionPane.showMessageDialog(this,"no more record in file",
                          "class not found",JOptionPane.ERROR_MESSAGE );
       }
       catch(ClassNotFoundException classNotFoundException)
       {
           JOptionPane.showMessageDialog(this,"Unable to Create Object",
                          "end of file",JOptionPane.ERROR_MESSAGE );
       }
        catch (IOException ioException)
        {
           JOptionPane.showMessageDialog(this,"error during read from file",
                          "read Error",JOptionPane.ERROR_MESSAGE );
        }
     }
    }
  }


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -