一个简单的Java画图工具 - 极悦
专注Java教育14年 全国咨询/投诉热线:444-1124-454
极悦LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 一个简单的Java画图工具

一个简单的Java画图工具

更新时间:2021-09-29 09:05:16 来源:极悦 浏览785次

有一个简单的工具来绘制基本的几何形状。该Java开发工具是使用 AWT 组件编写的,并详细阐述了诸如内部类、事件处理、多态性和菜单处理等功能。在本文中,我们将逐块逐步执行代码以构建我们的简单绘图工具。

第 1 步:空的类结构

首先,我们从一个空的类结构开始,我们从 java.awt.Frame 类扩展/继承它。我们设置框架的标题和大小并使其可见。

//Title:        A Simple Drawing Tool
//Version:      1.0
//Copyright:    Copyright (c) 2001
//Author:       Yasir Feroze Minhas
//Company:      KAPS Computing (pvt) Ltd.
//Description:  This is a simple tool written using AWT for drawing basic shapes.
package graph;
import java.awt.*;
public class SimpleDrawingTool extends Frame{
  public SimpleDrawingTool() {
    //set frame's title
    super("Simple Drawing Tool");
    //set frame size
    this.setSize(400, 400);
    //make this frame visible
    this.setVisible(true);
  }
  public static void main(String[] args) {
    SimpleDrawingTool simpleDrawingTool = new SimpleDrawingTool();
  }
}

第 2 步:添加菜单

接下来,我们将菜单栏附加到我们的绘图工具,并用最少的菜单项对其进行装饰。

//Title:        A Simple Drawing Tool
//Version:      1.0
//Copyright:    Copyright (c) 2001
//Author:       Yasir Feroze Minhas
//Company:      KAPS Computing (pvt) Ltd.
//Description:  This is a simple tool written using AWT for drawing basic shapes.
package graph;
import java.awt.*;
public class SimpleDrawingTool extends Frame{
  //constants for menu shortcuts
  private static final int kControlA = 65;
  private static final int kControlD = 68;
  private static final int kControlC = 67;
  private static final int kControlR = 82;
  private static final int kControlP = 80;
  private static final int kControlT = 84;
  private static final int kControlX = 88; 
  public SimpleDrawingTool() {
    //set frame's title
    super("Simple Drawing Tool");
    //add menu
    addMenu();
    //set frame size
    this.setSize(400, 400);
    //make this frame visible
    this.setVisible(true);
  }
  public static void main(String[] args) {
    SimpleDrawingTool simpleDrawingTool = new SimpleDrawingTool();
  }
  /**
  This method creates menu bar and menu items and then attach the menu bar
  with the frame of this drawing tool.
  */
  private void addMenu()
  {
    //Add menu bar to our frame
    MenuBar menuBar = new MenuBar();
    Menu file = new Menu("File");
    Menu shape = new Menu("Shapes");
    Menu about = new Menu("About");
    //now add menu items to these Menu objects
    file.add(new MenuItem("Exit", new MenuShortcut(kControlX)));
    shape.add(new MenuItem("Rectangle", new MenuShortcut(kControlR)));
    shape.add(new MenuItem("Circle", new MenuShortcut(kControlC)));
    shape.add(new MenuItem("Triangle", new MenuShortcut(kControlT)));
    shape.add(new MenuItem("Polygon", new MenuShortcut(kControlP)));
    shape.add(new MenuItem("Draw Polygon", new MenuShortcut(kControlD)));
    about.add(new MenuItem("About", new MenuShortcut(kControlA)));
    //add menus to menubar
    menuBar.add(file);
    menuBar.add(shape);
    menuBar.add(about);
    //menuBar.setVisible(true);
    if(null == this.getMenuBar())
    {
      this.setMenuBar(menuBar);
    }
  }//addMenu()
}

第 3 步:添加事件处理程序

菜单栏就位,您可以导航不同的菜单和菜单项。但由于它们尚未附加任何事件处理程序,因此您只能做导航。下一步是添加事件处理程序,以便我们可以捕获用户的选择并采取相应的行动。

package graph;
import java.awt.*;
//import event package
import java.awt.event.*;
//import swing package for pop up message box
import javax.swing.*;
public class SimpleDrawingTool extends Frame{
  ...
  private void addMenu()
  {
    ...
    file.add(new MenuItem("Exit", new MenuShortcut(kControlX))).addActionListener(new WindowHandler());
    shape.add(new MenuItem("Rectangle", new MenuShortcut(kControlR))).addActionListener(new WindowHandler());
    shape.add(new MenuItem("Circle", new MenuShortcut(kControlC))).addActionListener(new WindowHandler());
    shape.add(new MenuItem("Triangle", new MenuShortcut(kControlT))).addActionListener(new WindowHandler());
    shape.add(new MenuItem("Polygon", new MenuShortcut(kControlP))).addActionListener(new WindowHandler());
    shape.add(new MenuItem("Draw Polygon", new MenuShortcut(kControlD))).addActionListener(new WindowHandler());
    about.add(new MenuItem("About", new MenuShortcut(kControlA))).addActionListener(new WindowHandler());
    ...
  }
  ...
  //Inner class to handle events
  private class WindowHandler extends WindowAdapter implements ActionListener
  {
    public void windowClosing(WindowEvent e)
    {
      System.exit(0);
    }
    public void actionPerformed(ActionEvent e)
    {
      System.out.println(e.getActionCommand());
      //check to see if the action command is equal to exit
      if(e.getActionCommand().equalsIgnoreCase("exit"))
      {
        System.exit(0);
      }
      else if(e.getActionCommand().equalsIgnoreCase("About"))
      {
        JOptionPane.showMessageDialog(null, "This small freeware program is written by Yasir Feroze Minhas.", "About", JOptionPane.PLAIN_MESSAGE);
      }
      else
      {
        JOptionPane.showMessageDialog(null, "You asked for a "+e.getActionCommand(), "A Simple Drawing Tool", JOptionPane.PLAIN_MESSAGE);
      }
    }//actionPerformed()
  }//windowHandler - Inner Class ends here
}

第 4 步:编写一个 Shapes 类

现在是时候写下我们的 Shapes 类了。我们使用一种方法将 Shapes 类定义为抽象类draw(),然后将其扩展为 Rectangle、Oval、Triangle 和 Polygon 的具体类。然后我们使用多态根据传递的上述具体类的运行时对象绘制不同的形状。

/**
  This is the abstract parent class for different shape classes,
  like rectangle, oval, polygon and triangle. It provides an abstract
  method draw().
*/
package graph;
import java.util.*;
import java.awt.*;
public abstract class Shapes 
{
  /**abstract method draw()
    @return void
  */
  public abstract void draw(java.util.List list, Graphics g);
}
//different implementations of Shape class
class RectangleShape extends Shapes
{
  Point sPoint = null;
  Point ePoint = null;
  public void draw(java.util.List list, Graphics g)
  {
    Iterator it = list.iterator();
    //if the list does not contain the required two points, return.
    if(list.size()<2)
    {
      return;
    }
    sPoint = (Point)it.next();
    ePoint = (Point)it.next();
    if(sPoint == null || ePoint == null)
    {
      return;
    }
    else
    {
      g.fillRect((int)sPoint.getX(), (int)sPoint.getY(), (int)(ePoint.getX()-sPoint.getX()),
      (int)(ePoint.getY()-sPoint.getY()));
    }//end of if
    list.clear();
  }//end of draw for rectangle
}//rectangle
class OvalShape extends Shapes
{
  Point sPoint = null;
  Point ePoint = null;
  public void draw(java.util.List list, Graphics g)
  {
    Iterator it = list.iterator();
    //if the list does not contain the required two points, return.
    if(list.size()<2)
    {
      return;
    }
    sPoint = (Point)it.next();
    ePoint = (Point)it.next();
    if(sPoint == null || ePoint == null)
    {
      return;
    }
    else
    {
      g.fillOval((int)sPoint.getX(), (int)sPoint.getY(), (int)(ePoint.getX()-sPoint.getX()),
      (int)(ePoint.getY()-sPoint.getY()));
    }//end of if
    list.clear();
  }//end of draw for Oval
}//OvalShape
class TriangleShape extends Shapes
{
  public void draw(java.util.List list, Graphics g)
  {
    Point point = null;
    Iterator it = list.iterator();
    //if the list does not contain the required two points, return.
    if(list.size()<3)
    {
      return;
    }
    Polygon p = new Polygon();
    for(int i = 0; i < 3; i++)
    {
      point = (Point)it.next();
      p.addPoint((int)point.getX(), (int)point.getY());
    }
    g.fillPolygon(p);
    list.clear();
  }//end of draw for Triangle
}//Triangle
class PolygonShape extends Shapes
{
  public void draw(java.util.List list, Graphics g)
  {
    Point point = null;
    Iterator it = list.iterator();
    //if the list does not contain the required two points, return.
    if(list.size()<3)
    {
      return;
    }
    Polygon p = new Polygon();
    for(;it.hasNext();)
    {
      point = (Point)it.next();
      p.addPoint((int)point.getX(), (int)point.getY());
    }
    g.fillPolygon(p);
    list.clear();
  }//end of draw for Polygon
}//Polygon

步骤 5:添加用于绘制形状的面板并编写适当的事件处理程序

现在我们向我们的简单绘图工具添加一个面板并重写我们的 WindowHandler 类,以便它启用/禁用菜单选择并将相应的 Shapes 对象传递给面板进行绘图。这是actionPerformedSimpleDrawingTool 和 DrawingPanel 类的更改方法。

public void actionPerformed(ActionEvent e)
    {
      //check to see if the action command is equal to exit
      if(e.getActionCommand().equalsIgnoreCase("exit"))
      {
        System.exit(0);
      }
      else if(e.getActionCommand().equalsIgnoreCase("Rectangle"))
      {
        Menu menu = getMenuBar().getMenu(1);
        for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
        getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlR)).setEnabled(false);
        panel.drawShape(rectangle);
      }
      else if(e.getActionCommand().equalsIgnoreCase("Circle"))
      {
        Menu menu = getMenuBar().getMenu(1);
        for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
        getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlC)).setEnabled(false);
        panel.drawShape(oval);
      }
      else if(e.getActionCommand().equalsIgnoreCase("Triangle"))
      {
        Menu menu = getMenuBar().getMenu(1);
        for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
        getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlT)).setEnabled(false);
        panel.drawShape(triangle);
      }
      else if(e.getActionCommand().equalsIgnoreCase("Polygon"))
      {
        Menu menu = getMenuBar().getMenu(1);
        for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
        getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlP)).setEnabled(false);
        panel.drawShape(polygon);
      }
      else if(e.getActionCommand().equalsIgnoreCase("Draw Polygon"))
      {
        Menu menu = getMenuBar().getMenu(1);
        for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
        getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlP)).setEnabled(false);
        panel.repaint();
      }
      else if(e.getActionCommand().equalsIgnoreCase("About"))
      {
        JOptionPane.showMessageDialog(null, "This small freeware program is written by Yasir Feroze Minhas.", "About", JOptionPane.PLAIN_MESSAGE);
      }
    }//actionPerformed()
class DrawingPanel extends Panel implements MouseListener
{
  private Point sPoint = null;
  private Point ePoint = null;
  private Shapes shape = null;
  private java.util.ArrayList list = new java.util.ArrayList();
  //override panel paint method to draw shapes
  public void paint(Graphics g)
  {
    g.setColor(Color.green);
    shape.draw(list, g);
  }
  public void drawShape(Shapes shape)
  {
    this.shape = shape;
  }
  //define mouse handler
  public void mouseClicked(MouseEvent e)
  {
    //if user wants to draw triangle, call repaint after 3 clicks
    if(shape instanceof TriangleShape)
    {
      list.add(e.getPoint());
      if(list.size() > 2)
      {
        repaint();
      }
    }
    else if(shape instanceof PolygonShape)
    {
      list.add(e.getPoint());
    }
  }//mouseClicked
  public void mouseEntered(MouseEvent e){}
  public void mouseExited(MouseEvent e){}
  public void mousePressed(MouseEvent e)
  {
    sPoint = e.getPoint();
  }//mousePressed
  public void mouseReleased(MouseEvent e)
  {
    ePoint = e.getPoint();
    if(ePoint.getX() < sPoint.getX())
    {
      Point temp = ePoint;
      ePoint = sPoint;
      sPoint = temp;
    }
    if(ePoint.getY() < sPoint.getY())
    {
      int temp = (int)ePoint.getY();
      ePoint.y = (int)sPoint.getY();
      sPoint.y = temp;
    }
    if(shape instanceof RectangleShape || shape instanceof OvalShape)
    {
      list.clear();
      list.add(sPoint);
      list.add(ePoint);
      repaint();
    }
  }//mouseReleased
}//DrawingPanel

现在我们完成了我们的 SimpleDrawingTool,并且可以使用鼠标在其面板上绘制基本的几何形状。然而,这段代码仍然存在一些问题,我们将在下一版本的 SimpleDrawingTool 中回来重新审视这段代码,并增强它以包括填充颜色选择和鼠标移动跟踪线,同时绘制具有更好菜单的形状对象选择选项。

Java学习中会运用到很的开发工具,大家可都要熟练使用哦。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>