You are on page 1of 27

Digital Drawing Tools using Java

A PROJECT REPORT

Submitted by

ATUL KUMAR MAURYA


REGD. NO: 8707639833

in partial fulfillment for the award of the degree

of

Diploma (3years)

in

COMPUTER SCIENCE & ENGINEERING

GOV POLYTECHINC PREMDHARPATTI


PRATPGARH

1
Ducat IT TRAINING INSTITUTE
Mohan nagar Ghaziabad, Uttar Pradesh, India

CERTIFICATE

This is to certified that the project report “CIG: A Digital drawing tools using

java” being submitted by “Atul kumar maurya” bearing registration number:

8707639833, in partial fulfillment of requirement for the award of degree of

Diploma(3 years) in CSE is a bonafide work carried out under my/our

supervision.

Rajiv sishodiya
Atul kumar maurya
JAVA Trainer (OCJP Certified)
Student of CSE & IT
Gov polytechnic premdhar patti
pratrapgarh

External Examiner Signature

2
Ducat IT TRAINING INSTITUTE
Mohan nagar Ghaziabad, Uttar Pradesh, India

CERTIFICATE

This is to certify that Mr. Atul kumar maurya bearing registration number:

0805297005, has successfully developed a project on “A Digital drawing tools

using java” under our guidance. His skill set, knowledge on software and sincere

effort has contributed towards successful completion of the project.

Mr. Rajiv Sishodiya


EXTERNAL SUPERVISOR
Project Leader
Ducat Mohan nagar Ghaziabad

3
Ducat IT TRAINING INSTITUTE
Mohan nagar Ghaziabad, Uttar Pradesh, India
CERTIFICATE

I hereby declare that the matter embodied in this report is original and has not been

submitted for the award of any other degree

Atul kumar maurya


Regd. No. : 8707639833
Department of CSE

4
Acknowledgement
I take this opportunity with much pleasure to thank all the people who have helped
me through the course of my journey towards producing this thesis. I sincerely
thank my thesis guide, Prof. Abhishek bjaj And chandan Sir, for his guidance,
help and motivation. Apart from the subject of my research, I learnt a lot from him,
which I am sure will be useful in different stages of my life. I would like to express
my gratitude to Prof. Vivek singh for his review and many helpful comments.

I am especially grateful to my colleagues for their assistance, criticisms and useful


insights.. I would like to acknowledge the support and encouragement of my
friends. My sincere gratitude also goes to all those who instructed and taught me
through the years.

Finally, this thesis would not have been possible without the confidence, endurance
and support of my family. My family has always been a source of inspiration and
encouragement. I wish to thank my parents, whose love, teachings and support
have brought me this far.

Name of the Student

Atul kumar maurya

5
Contents

 Introduction to the Paint Application


 Setting Up the Paint Application
 Creating the Application Skeleton

 Creating the Module

Creating and Embedding the Paint Canvas


 Creating the Canvas

 Embedding the Canvas in a Window

Running, Branding, and Packaging the Application


 Running the Application

 Branding the Application

 Packaging the Application

6
Introduction to the Paint Application

This initial version is far from a full fledged paint application, but it demonstrates a
very simple case of creating an application on top of the NetBeans Platform.

Software or Resource Version Required


NetBeans IDE version 8.0 or above
Java Developer Kit (JDK) version 7 or above

7
Setting Up the Paint Application
In this section, you create the structure of your application. You first need to create
an application skeleton, which you can do via a wizard. Then you will create the
module that will contain your code.
Creating the Application Skeleton
The "NetBeans Platform Application" template will create your application's
skeleton. The skeleton will consist of a set of modules that work together to form
the basis of your application. You will use the Project Properties dialog to assign
your application's splashscreen, application name, and the type and number of
NetBeans modules that you want to use. You can also take advantage of such
actions as creating a ZIP distribution and building a Java WebStart (JNLP)
application, which are important tools in making your application available to
other users.
1. Choose File > New Project. Under Categories, select NetBeans Modules. Under
projects, select NetBeans Platform Application:

8
Click Next.
2. In the Name and Location panel, type PaintApp in Project Name. Change the
Project Location to any directory on your computer:

Click Finish.
3. The new application skeleton opens in the IDE. Look at the new project structure:

You see two subnodes in the Projects window. The first subnode, the "Modules"
node, shows you the custom modules that are part of the application. Right now, as
you can see, there are none. You can right-click on this subnode and then invoke
wizards for creating new modules or for wrapping external JARs into the
application. The "Important Files" node shows the build scripts and other
supporting files used by the application.

4. Right-click the application and choose Run. The default splash screen is shown and
then you see the starting point of your new application:

9
Look through the menu bar and the toolbar to see the features that your application
already has, such as an Exit menu item, a Properties window, and an Output
window.

Creating the Functionality Module


Now you need a module to contain the actual code you're going to write.
1. Right-click the "Modules" node in the Paint Application. Select Add New:

2. In the Name and Location panel, type Paint in Project Name.

10
Notice that the module sources will be stored within a folder in the application's
directory on disk. Click Next.
3. In the Basic Module Configuration panel, type org.netbeans.paint as the "Code
Name Base". The code name base is a unique string identifying the module to other
modules in the application. Leave everything unchanged.

Click Finish. The IDE creates the Paint project.


4. Take a look at the structure of your application. The project contains all of your
sources and project metadata, such as the project's Ant build script. The project
opens in the IDE. You can view its logical structure in the Projects window (Ctrl-
1) and its file structure in the Files window (Ctrl-2). For example, the Projects
window should look as follows:

11
5. You will need to
Class API Purpose subclass several
Lookup Enables loosely coupled classes that
Lookup
API communication between modules. belong to
Provides annotations for registering the NetBeans
UI
Actions in the NetBeans Platform APIs. All
ActionID Utilities
virtual filesystem, as well as NetBeans APIs
API
the ColorComboBox class. are implemented
Provides a variety of general utility by modules, so
Utilities classes, including support for this task really
Messages
API internationalization via the Bundle just means adding
class and @Messages annotation. some modules to
Window the list of
Gives you access to the NetBeans
TopComponent System modules that our
window system.
API module needs in
order to run. In the Projects window, right-click the Paint project node and choose
Properties. The Project Properties dialog box opens. Under Categories, click
Libraries. For each of the API's listed in the table below, click "Add
Dependency..." and then, in the Filter text box, start typing the name of the class
that you want to subclass.

12
The first column in the table above lists all the classes that you will subclass in this
tutorial. In each case, start typing the class name in the Filter and watch the
Module list narrow. Use the table's second column to pick the appropriate API (or,
in the case of ColorChooser, the library) from the narrowed Module list and then
click OK to confirm the choice. Click OK to exit the Project Properties dialog box.
In the Projects window, expand the Paint module's project node and then expand
the Libraries node. Notice that all the libraries you have selected are displayed:
Expand the Paint module's Important Files node and double-click the Project
Metadata node. Notice that the API's you selected have been declared as module
dependencies in the file. When the module is compiled, the declared dependencies
are added to the module's manifest file.

Creating and Embedding the Paint Canvas


Creating the Canvas
The next step is to create the actual component on which the user can paint. Here,
you use a pure Swing component—so, let's skip the details of its implementation
and just provide the final version. The color chooser bean, which you created the
library wrapper module for, is used in the source code for this panel—when you
run the finished application, you will see it in the toolbar of the panel for editing
images.
1. In the Projects window, expand the Paint node, then expand the Source Packages
node, and then right-click the org.netbeans.paintnode. Choose New > Java Class.
2. Enter PaintCanvas as the Class Name. Ensure that org.netbeans.paint is listed as
the Package. Click Finish. PaintCanvas.java opens in the Source editor.

13
3. Replace the default content of the file with the content found here. If you named
your package something other than org.netbeans.paint, correct the package name in
the Source editor.

Embedding the Canvas in a Window


Now you'll write the only class in this application that needs to touch the NetBeans
APIs. It is a TopComponent class. A TopComponent class is just a JPanel class
which the NetBeans windowing system knows how to talk to—so that it can be put
inside a tabbed container inside the main window.

1. In the Projects window, expand the Paint node, then expand the Source Packages
node, and then right-click the org.netbeans.paintnode. Choose New > Java Class.
Enter PaintTopComponent as the Class Name. Ensure that org.netbeans.paint is
listed as the Package. Click Finish. PaintTopComponent.java opens in the Source
editor.

2. Near the top of the file, change the class declaration to the following:
public class PaintTopComponent extends TopComponent implements
ActionListener, ChangeListener {
3. Press Ctrl-Shift-I to fix imports and click OK. The IDE makes the necessary
import package declarations at the top of the file:
import java.awt.event.ActionListener;
import javax.swing.event.ChangeListener;
import org.openide.windows.TopComponent;

Notice the red line under the class declaration that you just entered. Position the
cursor in the line and notice that a light bulb appears in the left margin. Click the
light bulb (or press Alt-Enter), as shown below:

14
Select Implement all abstract methods. The IDE generates two method skeletons—
actionPerformed() and stateChanged(). You will fill these out later in this tutorial.
4. Register the PaintTopComponent in the window system by adding annotations to
the top of the class, as shown here, and then press Ctrl-Shift-I to let the IDE
generate the appropriate import statements:
@TopComponent.Description(
preferredID = "PaintTopComponent",
iconBase = "/org/netbeans/paint/new_icon.png",
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(
mode = "editor",
openAtStartup = true)
@ActionID(
category = "Window",
id = "org.netbeans.paint.PaintTopComponent")
@ActionReferences({
@ActionReference(
path = "Menu/Window",
position = 0),
@ActionReference(
path = "Toolbars/File",
position = 0)
})
@TopComponent.OpenActionRegistration(
displayName = "#CTL_NewCanvasAction")
@Messages({
"CTL_NewCanvasAction=New Canvas",
"LBL_Clear=Clear",
"LBL_Foreground=Foreground",
"LBL_BrushSize=Brush Size",
"# {0} - image",
"UnsavedImageNameFormat=Image {0}"})
public class PaintTopComponent extends TopComponent implements
ActionListener, ChangeListener {

Note: While the module is being compiled, the annotations above will be
processed. XML entries will be created in the module's generated-layer.xml file,
for each of the @TopComponent* and @Action* annotations. The generated-
layer.xml file will be contributed by the module to the System Filesystem of the
application. Read more about the System Filesystem here. For example,
the PaintTopComponent will be displayed in the main area of the application,
defined by the "editor" position, as specified by
15
the @TopComponent.Registration annotation above. For each item defined in
the @Messages annotation, a new key/value string is generated into
a Bundle.java class.
5. Add these two icons to "org/netbeans/paint":

The 16x16 pixel icon will be used for the Small Toolbar Icons display, while the
24x24 pixel icon will be used for the Large Toolbar display, as well as in the tab of
the window, as defined by @TopComponent.Description above.
6. The TopComponent class is a wrapper for the Canvas you created earlier. All the
new import statements and code below is normal Java Swing code. Copy it below
and paste it into your PaintTopComponent source file:
package org.netbeans.paint;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JToolBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

16
import org.netbeans.api.settings.ConvertAsProperties;
import org.netbeans.swing.colorchooser.ColorChooser;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.StatusDisplayer;
import org.openide.cookies.SaveCookie;
import org.openide.filesystems.FileChooserBuilder;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;
import org.openide.windows.TopComponent;

@ConvertAsProperties(dtd = "-
//org.netbeans.paint//PaintTopComponent//EN", autostore = false)
@TopComponent.Description(preferredID = "PaintTopComponent",
iconBase = "/org/netbeans/paint/new_icon.png", persistenceType =
TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = true)
@ActionID(category = "Window", id =
"org.netbeans.paint.PaintTopComponent")
@ActionReferences({
@ActionReference(path = "Menu/Window", position = 0),
@ActionReference(path = "Toolbars/File", position = 0)
})
@TopComponent.OpenActionRegistration(displayName =
"#CTL_NewCanvasAction")
17
public final class PaintTopComponent extends TopComponent
implements ActionListener, ChangeListener {
private static int ct = 0; //A counter you use to provide names for new
images
private final PaintCanvas canvas = new PaintCanvas(); //The
component the user draws on
private final JComponent preview = canvas.getBrushSizeView(); //A
component in the toolbar that shows the paintbrush size
private final JToolBar toolbar = new JToolBar(); //The toolbar
private final ColorChooser color = new ColorChooser(); //Our color
chooser component from the ColorChooser library
private final JButton clear = new JButton(
NbBundle.getMessage(PaintTopComponent.class, "LBL_Clear"));
//A button to clear the canvas
private final JLabel label = new JLabel(
NbBundle.getMessage(PaintTopComponent.class,
"LBL_Foreground")); //A label for the color chooser
private final JLabel brushSizeLabel = new JLabel(
NbBundle.getMessage(PaintTopComponent.class,
"LBL_BrushSize")); //A label for the brush size slider
private final JSlider brushSizeSlider = new JSlider(1, 24); //A slider to
set the brush size
private InstanceContent content = new InstanceContent(); //The bag of
stuff we add/remove the Saver from, and store the last-used file in
private Saver saver = new Saver();

public PaintTopComponent() {
initComponents();
String displayName = NbBundle.getMessage(
PaintTopComponent.class,
"UnsavedImageNameFormat", ct++);
setDisplayName(displayName);

18
//If we don't set the name, Window > Documents will throw an
exception
setName(displayName);

//Connect our lookup to the rest of the system, so that


//SaveAction will pay attention to whether or not the Saver is
available
associateLookup(new AbstractLookup(content));
//Enable the Print action for the canvas:
putClientProperty("print.printable", true);
//Disable the Save action by default:
enableSaveAction(false);
}

private void initComponents() {


setLayout(new BorderLayout());
//Configure our components, attach listeners
color.addActionListener(this);
clear.addActionListener(this);
brushSizeSlider.setValue(canvas.getBrushDiameter());
brushSizeSlider.addChangeListener(this);
color.setColor(canvas.getColor());
color.setMaximumSize(new Dimension(16, 16));
//Install the toolbar and the painting component:
add(toolbar, BorderLayout.NORTH);
add(new JScrollPane(canvas), BorderLayout.CENTER);
//Configure the toolbar
toolbar.setLayout(new FlowLayout(FlowLayout.LEFT, 7, 7));
toolbar.setFloatable(false);
//Now populate our toolbar:
toolbar.add(label);
toolbar.add(color);
19
toolbar.add(brushSizeLabel);
toolbar.add(brushSizeSlider);
toolbar.add(preview);
toolbar.add(clear);
}

private void enableSaveAction(boolean canSave) {


if (canSave) {
//If the canvas is modified,
//we add SaveCookie impl to Lookup:
content.add(saver);
} else {
//Otherwise, we remove the SaveCookie impl from the lookup:
content.remove(saver);
canvas.addMouseListener(new MouseAdapter() {

@Override
public void mouseReleased(MouseEvent e) {
//Once we can save, we are done listening.
//If enableSaveAction(false) is called, we will
//start listening again.
canvas.removeMouseListener(this);
enableSaveAction(true);
}
});
}
}

@Override
public void stateChanged(ChangeEvent e) {
canvas.setBrushDiameter(brushSizeSlider.getValue());

20
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
canvas.clear();

enableSaveAction(false);
} else if (e.getSource() instanceof ColorChooser) {
ColorChooser cc = (ColorChooser) e.getSource();
canvas.setColor(cc.getColor());
}
}

private class Saver implements SaveCookie {

@Override
public void save() throws IOException {
DataObject theFile = getLookup().lookup(DataObject.class);
if (theFile != null) {
File saveTo = FileUtil.toFile(theFile.getPrimaryFile());
save(saveTo);
} else {
saveAs();
}
}

public void saveAs() throws IOException {


String title = NbBundle.getMessage(Saver.class,
"TTL_SAVE_DIALOG");
File f = new
FileChooserBuilder(Saver.class).setTitle(title).showSaveDialog();
21
if (f != null) {
if (!f.getAbsolutePath().endsWith(".png")) {
f = new File(f.getAbsolutePath() + ".png");
}
try {
if (!f.exists()) {
if (!f.createNewFile()) {
String failMsg = NbBundle.getMessage(

PaintTopComponent.class,
"MSG_SaveFailed", f.getName());
DialogDisplayer.getDefault().notify(new
NotifyDescriptor.Message(failMsg));
return;
}
} else {
String overwriteMessage =
NbBundle.getMessage(Saver.class, "MSG_Overwrite", f.getName());
Object userChose =
DialogDisplayer.getDefault().notify(new
NotifyDescriptor.Confirmation(overwriteMessage));
if
(NotifyDescriptor.CANCEL_OPTION.equals(userChose)) {
return;
}
}
//Need getAbsoluteFile(), or X.png and x.png are different on
windows
save(f.getAbsoluteFile());
} catch (IOException ioe) {
Exceptions.printStackTrace(ioe);
}
}
22
}

private void save(File f) throws IOException {


ImageIO.write(canvas.getImage(), "png", f);
String savedMessage = NbBundle.getMessage(Saver.class,
"MSG_Saved", f.getName());
StatusDisplayer.getDefault().setStatusText(savedMessage);
FileObject fob = FileUtil.toFileObject(FileUtil.normalizeFile(f));
assert fob != null : "MasterFS excluded from suite?";
//Store the file, so we don't show the Save dialog again
content.add(DataObject.find(fob));
setDisplayName(fob.getName());
enableSaveAction(false);
}
}

void writeProperties(java.util.Properties p) {

p.setProperty("version", "1.0");
// now store the color and size
p.setProperty("color", "" + color.getColor().getRGB());
p.setProperty("size", "" + brushSizeSlider.getValue());
}

void readProperties(java.util.Properties p) {
String version = p.getProperty("version");
assert "1.0".equals(version);
final String rgbRef = p.getProperty("color");
final String sizeRef = p.getProperty("size");
if (rgbRef != null) {
int rgb = Integer.parseInt(rgbRef);
final Color c = new Color(rgb);
23
color.setColor(c);
canvas.setColor(c);
}
if (sizeRef != null) {
int size = Integer.parseInt(sizeRef);
brushSizeSlider.setValue(size);
canvas.setBrushDiameter(size);
}
}
}

Running, Branding, and Packaging the Application


In this section, you try out the application and then package it for distribution to
your users.
Running the Application
1. Right-click the application and choose Run:

2. The application starts up, a splash screen is displayed, and then your application is
shown. Paint something, as shown below:

24
3. Use the application and try to identify areas where you'd like to provide more
functionality.

Branding the Application


1. Right-click the application and choose Branding.
2. The Branding Window is shown, use it to change icons, the splash screen, the
window features, and the strings displayed in the application:

25
Packaging the Application

1. Right-click the application and choose Package as:

26
2. Choose the distribution mechanism relevant to your business needs and your user
requirements.
3. Switch to the Files window (Ctrl-2) to see the result.

27