How To Create Java Drawing Pad
Recently, while I was doodling with Java code, I wrote this simple tool for drawing basic geometric shapes. This tool is written using AWT components and elaborates features such as inner classes, effect handling, polymorphism, and menu handling. In this article, we will stride through the lawmaking chunk by chunk to build our unproblematic cartoon tool.
Pace ane: An Empty Grade Structure
First, we start with an empty grade structure and we extend/inherit it from java.awt.Frame class. We set the frame'due south title and size and brand it visible.
//Championship: A Simple Drawing Tool //Version: 1.0 //Copyright: Copyright (c) 2001 //Author: Yasir Feroze Minhas //Visitor: KAPS Computing (pvt) Ltd. //Description: This is a elementary tool written using AWT for drawing basic shapes. parcel graph; import java.awt.*; public class SimpleDrawingTool extends Frame{ public SimpleDrawingTool() { //gear up frame's title super("Uncomplicated Cartoon Tool"); //set frame size this.setSize(400, 400); //make this frame visible this.setVisible(true); } public static void principal(String[] args) { SimpleDrawingTool simpleDrawingTool = new SimpleDrawingTool(); } }
Step 2: Adding Menus
Adjacent, nosotros attach a menu bar to our cartoon tool and decorate it with the minimal required menu items.
//Title: A Simple Drawing Tool //Version: 1.0 //Copyright: Copyright (c) 2001 //Writer: Yasir Feroze Minhas //Company: KAPS Computing (pvt) Ltd. //Description: This is a simple tool written using AWT for drawing bones shapes. packet graph; import coffee.awt.*; public course SimpleDrawingTool extends Frame{ //constants for menu shortcuts private static final int kControlA = 65; private static final int kControlD = 68; private static terminal int kControlC = 67; private static final int kControlR = 82; private static final int kControlP = eighty; individual static final int kControlT = 84; individual static final int kControlX = 88; public SimpleDrawingTool() { //ready frame'south title super("Unproblematic Drawing Tool"); //add together carte du jour addMenu(); //ready 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 bill of fare bar with the frame of this drawing tool. */ private void addMenu() { //Add carte 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 bill of fare items to these Bill of fare objects file.add(new MenuItem("Exit", new MenuShortcut(kControlX))); shape.add together(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))); nearly.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() }
Step iii: Adding Event Handlers
The card bar is in place, and you tin navigate unlike menus and card items. But since they are not even so attached with any result handler, y'all can not do much more than than navigation. Out next step is to add together result handlers so we can trap user choices and act appropriately.
package graph; import java.awt.*; //import event package import coffee.awt.event.*; //import swing package for pop up message box import javax.swing.*; public form SimpleDrawingTool extends Frame{ ... private void addMenu() { ... file.add(new MenuItem("Get out", new MenuShortcut(kControlX))).addActionListener(new WindowHandler()); shape.add together(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 together(new MenuItem("Draw Polygon", new MenuShortcut(kControlD))).addActionListener(new WindowHandler()); about.add together(new MenuItem("Well-nigh", new MenuShortcut(kControlA))).addActionListener(new WindowHandler()); ... } ... //Inner class to handle events private class WindowHandler extends WindowAdapter implements ActionListener { public void windowClosing(WindowEvent east) { System.leave(0); } public void actionPerformed(ActionEvent eastward) { System.out.println(e.getActionCommand()); //cheque to see if the activity control is equal to get out if(e.getActionCommand().equalsIgnoreCase("get out")) { Organization.exit(0); } else if(e.getActionCommand().equalsIgnoreCase("About")) { JOptionPane.showMessageDialog(nada, "This modest freeware programme is written by Yasir Feroze Minhas.", "About", JOptionPane.PLAIN_MESSAGE); } else { JOptionPane.showMessageDialog(naught, "Y'all asked for a "+e.getActionCommand(), "A Uncomplicated Cartoon Tool", JOptionPane.PLAIN_MESSAGE); } }//actionPerformed() }//windowHandler - Inner Class ends here }
Step 4: Writing a Shapes Grade
Now its fourth dimension to write downwards our Shapes grade. We define our Shapes class as abstract with 1 method, draw()
, and then extend information technology to concrete classes of Rectangle, Oval, Triangle, and Polygon. Nosotros and so use polymorphism to describe different shapes depending upon the runtime object of the in a higher place concrete classes passed.
/** This is the abstract parent form 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 describe() @return void */ public abstruse void draw(java.util.List list, Graphics g); } //different implementations of Shape grade class RectangleShape extends Shapes { Point sPoint = null; Point ePoint = null; public void describe(java.util.List list, Graphics one thousand) { Iterator it = listing.iterator(); //if the list does non contain the required ii points, render. if(list.size()<ii) { return; } sPoint = (Point)it.next(); ePoint = (Point)it.next(); if(sPoint == null || ePoint == nada) { render; } else { thou.fillRect((int)sPoint.getX(), (int)sPoint.getY(), (int)(ePoint.getX()-sPoint.getX()), (int)(ePoint.getY()-sPoint.getY())); }//finish of if list.clear(); }//finish of draw for rectangle }//rectangle class OvalShape extends Shapes { Point sPoint = null; Point ePoint = null; public void draw(coffee.util.List list, Graphics g) { Iterator it = list.iterator(); //if the list does not contain the required ii points, render. if(listing.size()<2) { return; } sPoint = (Point)it.adjacent(); ePoint = (Point)it.next(); if(sPoint == null || ePoint == null) { return; } else { thousand.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 depict(java.util.List listing, Graphics k) { Betoken point = null; Iterator information technology = list.iterator(); //if the list does not comprise the required two points, return. if(listing.size()<three) { return; } Polygon p = new Polygon(); for(int i = 0; i < 3; i++) { indicate = (Bespeak)information technology.next(); p.addPoint((int)betoken.getX(), (int)bespeak.getY()); } thou.fillPolygon(p); list.clear(); }//end of depict for Triangle }//Triangle class PolygonShape extends Shapes { public void draw(coffee.util.List listing, Graphics thousand) { Bespeak bespeak = zip; Iterator information technology = 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)betoken.getX(), (int)point.getY()); } g.fillPolygon(p); list.articulate(); }//end of draw for Polygon }//Polygon
Step five: Add together a Panel for Drawing Shapes and Write Proper Event Handlers
Now we add a panel to our simple drawing tool and rewrite our WindowHandler class then that it enables/disables bill of fare option and passes the corresponding Shapes object to panel for drawing. Here is a changed actionPerformed
method for the SimpleDrawingTool and DrawingPanel classes.
public void actionPerformed(ActionEvent e) { //check to see if the action control is equal to exit if(e.getActionCommand().equalsIgnoreCase("exit")) { System.exit(0); } else if(e.getActionCommand().equalsIgnoreCase("Rectangle")) { Menu menu = getMenuBar().getMenu(one); for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(truthful),i++); getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlR)).setEnabled(false); panel.drawShape(rectangle); } else if(due east.getActionCommand().equalsIgnoreCase("Circle")) { Carte du jour bill of fare = getMenuBar().getMenu(1); for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(truthful),i++); getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlC)).setEnabled(false); panel.drawShape(oval); } else if(due east.getActionCommand().equalsIgnoreCase("Triangle")) { Menu menu = getMenuBar().getMenu(1); for(int i = 0;i < carte.getItemCount();menu.getItem(i).setEnabled(truthful),i++); getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlT)).setEnabled(imitation); panel.drawShape(triangle); } else if(due east.getActionCommand().equalsIgnoreCase("Polygon")) { Menu bill of fare = getMenuBar().getMenu(one); for(int i = 0;i < bill of fare.getItemCount();bill of fare.getItem(i).setEnabled(true),i++); getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlP)).setEnabled(false); panel.drawShape(polygon); } else if(east.getActionCommand().equalsIgnoreCase("Draw Polygon")) { Menu menu = getMenuBar().getMenu(one); for(int i = 0;i < bill of fare.getItemCount();bill of fare.getItem(i).setEnabled(true),i++); getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlP)).setEnabled(false); panel.repaint(); } else if(e.getActionCommand().equalsIgnoreCase("About")) { JOptionPane.showMessageDialog(null, "This modest freeware program is written by Yasir Feroze Minhas.", "About", JOptionPane.PLAIN_MESSAGE); } }//actionPerformed() grade DrawingPanel extends Panel implements MouseListener { private Betoken sPoint = null; private Point ePoint = naught; private Shapes shape = nix; private coffee.util.ArrayList list = new java.util.ArrayList(); //override panel pigment method to draw shapes public void paint(Graphics k) { one thousand.setColor(Color.greenish); 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 later three clicks if(shape instanceof TriangleShape) { list.add(due east.getPoint()); if(list.size() > two) { repaint(); } } else if(shape instanceof PolygonShape) { list.add together(e.getPoint()); } }//mouseClicked public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent due east){} public void mousePressed(MouseEvent e) { sPoint = e.getPoint(); }//mousePressed public void mouseReleased(MouseEvent e) { ePoint = e.getPoint(); if(ePoint.getX() < sPoint.getX()) { Indicate 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.articulate(); list.add(sPoint); list.add together(ePoint); repaint(); } }//mouseReleased }//DrawingPanel
Now we are done with our SimpleDrawingTool and can depict basic geometric shapes on its console using a mouse. However, there are still some problems left in this code, and nosotros will come up back and revisit this code in the next release of SimpleDrawingTool and enhance it to include a fill color choice, and mouse movement tracing lines while cartoon a shape object with better menu pick options.
Download
- Zipped Code
- SimpleDrawingTool.java
- Shapes.java
About the Author
Yasir Feroze Minhas is a principal software engineer with KAPS Computing Ltd. (Pakistan), currently
working on Enterprise Resource Planning systems.
Minhas has a B.S. in informatics from FAST ICS, Lahore, Islamic republic of pakistan.
Source: https://www.developer.com/guides/a-simple-java-drawing-tool/
Posted by: ranasion1950.blogspot.com
0 Response to "How To Create Java Drawing Pad"
Post a Comment