blob: ef9bd06fa99ee16424f532b726bc15c5fb440784 [file] [log] [blame]
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
= NetBeans Platform Paint Application Tutorial
:jbake-type: platform_tutorial
:jbake-tags: tutorials
:jbake-status: published
:syntax: true
:source-highlighter: pygments
:toc: left
:toc-title:
:icons: font
:experimental:
:description: NetBeans Platform Paint Application Tutorial - Apache NetBeans
:keywords: Apache NetBeans Platform, Platform Tutorials, NetBeans Platform Paint Application Tutorial
This tutorial takes you through the basics of using NetBeans IDE to develop rich-client applications on top of the NetBeans Platform. When you develop applications on top of the NetBeans Platform, you are developing on top of the NetBeans IDE's core. All the modules belonging to the IDE that are not relevant to your application are excluded, but those that are useful are kept. By reusing features readily available in IDE's core, you save yourself a lot of time and energy.
NOTE: This document uses the NetBeans IDE 7.0 Release or above. If you are using an earlier version, see link:691/nbm-paintapp.html[the previous version of this document].
== Introduction to the Paint Application
This tutorial is designed to get you going as quickly as possible. You will create a simple application on the NetBeans Platform. The application allows the user to paint on the screen:
image::images/paintapp_70_result-without-menus.png[]
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.
NOTE: The link:nbm-google.html[NetBeans Plugin Quick Start] is a better tutorial for you if, instead of rich-client applications, you want to learn about NetBeans modules.
In this tutorial, we recreate an application that is a sample delivered with the IDE. To see the final product, or to troubleshoot problems while working through this tutorial, get the sample from the New Project wizard. Go to File | New Project, then Samples | NetBeans Modules | Paint Application, shown below:
image::images/paintapp_70_sample-in-new-project.png[]
== 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. The application depends on a library, so you will also create a library wrapper module that will contain the library's JAR file. Finally, 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.
[start=1]
1. Choose File > New Project. Under Categories, select NetBeans Modules. Under projects, select NetBeans Platform Application:
image::images/paintapp_70_paintapp-proj-wiz.png[]
Click Next.
[start=2]
1. In the Name and Location panel, type ``PaintApp`` in Project Name. Change the Project Location to any directory on your computer. Check the Set as Main Project checkbox. Click Finish.
[start=3]
1.
The new application skeleton opens in the IDE. Look at the new project structure:
image::images/paintapp_70_paintapp-proj-wiz2.png[]
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. modules to the application. The "Important Files" node shows the build scripts and other supporting files used by the application.
Now that we have an application, let's include an external JAR file that will be useful in our Paint Application.
=== Creating the Library Wrapper Module
A library wrapper module is a module whose JAR file contains no code—it is just a pointer to a library. It turns the library into a NetBeans module, so that all the protections of the NetBeans classloader system apply to it—without modifying the original JAR file. Your application can then depend on the library just as if the library were just another NetBeans module. And, if new versions of the library become available, you can distribute them without needing to distribute anything except a single NetBeans Module (NBM) file for the wrapper library.
NOTE: One of the benefits of building on the NetBeans Platform is that its user interface is based on Swing—the standard user interface toolkit for Java. Since Swing has been around for a long time, there are a lot of Swing components you can reuse in your application. In this tutorial, you reuse an existing color chooser JavaBean (you can find the source for it in NetBeans CVS under ``contrib/coloreditor`` ). The JAR file is called ``ColorChooser.jar`` . You can download the library here:
link:http://web.archive.org/web/20120107130444/http://java.net:80/projects/colorchooser/sources/svn/show/trunk/www/release?rev=82[http://java.net/projects/colorchooser/sources/svn/show/trunk/www/release?rev=82]
Save it anywhere in your filesystem.
Do the following to create a library wrapper module for the ``ColorChooser.jar`` file:
[start=1]
1. Right-click the "Modules" node in the Paint Application. Select Add New Library.
[start=2]
1.
In the Select Library panel, in the "Library" text box, either type in the path to ``ColorChooser.jar`` or browse to its location. Leave the "License" text field empty. If you intend to distribute the completed product, you should include the external library's license file.
image::images/paintapp_70_paintapp-lib-wiz1.png[]
Click Next.
[start=3]
1. In the Name and Location panel, fill in the project name, set the project location, and notice that the "Add to Module Suite" drop-down shows that the module will be added to the application.
image::images/paintapp_70_paintapp-lib-wiz2.png[]
Click Next.
[start=4]
1. In the Basic Module Configuration panel, type a unique name in the code name base, specify a module display name, and accept the suggested location of the module's localizing bundle:
image::images/paintapp_70_paintapp-lib-wiz3.png[]
Click Finish.
The module that wraps the selected ``colorchooser.jar`` is created by the IDE. The structure of the new module is shown in the Projects window. The "Modules" node in the application's structure shows that the module is part of the application.
=== Creating the Functionality Module
Now you need a module to contain the actual code you're going to write.
[start=1]
1. Right-click the "Modules" node in the Paint Application. Select Add New.
[start=2]
1.
In the Name and Location panel, type ``Paint`` in Project Name.
image::images/paintapp_70_paintapp-mod-wiz1.png[]
Notice that the module sources will be stored within a folder in the application's directory on disk. Click Next.
[start=3]
1. 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 and you should see the following:
image::images/paintapp_70_paintapp-mod-wiz2.png[]
Click Finish. The IDE creates the ``Paint`` project.
[start=4]
1. 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:
image::images/paintapp_70_paintapp-mod-wiz3.png[]
You have created the application structure. Let's now add some code!
=== Specifying the Module's Dependencies
You will need to subclass several classes that belong to the link:http://bits.netbeans.org/dev/javadoc/index.html[NetBeans APIs]. In addition, the project depends on the ``ColorChooser.jar`` file. All NetBeans APIs are implemented by modules, so completing both of these tasks really just means adding some modules to the list of modules that our module needs in order to run.
[start=1]
1. In the Projects window, right-click the ``Paint`` project node and choose Properties. The Project Properties dialog box opens. Under Categories, click Libraries.
[start=2]
1.
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.
|===
|*Class* |*API* |*Purpose*
| ``ColorChooser`` | ``ColorChooser`` |Library wrapper module for the color chooser component you created.
| ``Lookup`` | ``Lookup API`` |Enables loosely coupled communication between modules.
| ``ActionID`` | ``UI Utilities API`` |Provides annotations for registering Actions in the NetBeans Platform virtual filesystem.
| ``Messages`` | ``Utilities API`` |Provides a variety of general utility classes, including support for internationalization via the Bundle class and @Messages annotation.
| ``TopComponent`` | ``Window System API`` |Gives you access to the NetBeans window system.
|===
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.
[start=3]
1. 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:
image::images/paintapp_70_libfilter2.png[]
[start=4]
1. 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.
== 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.
[start=1]
1. In the Projects window, expand the ``Paint`` node, then expand the Source Packages node, and then right-click the ``org.netbeans.paint`` node. Choose New > Java Class.
[start=2]
1. 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.
[start=3]
1. Replace the default content of the file with the content found link:images/paintapp_70_PaintCanvas.java[here]. If you named your package something other than ``org.netbeans.paint`` , correct the package name in the Source editor.
=== Preparing the TopComponent Class
Now you'll write the only class in this application that needs to touch the link:http://bits.netbeans.org/dev/javadoc/index.html[NetBeans APIs]. It is a `` link:http://bits.netbeans.org/dev/javadoc/org-openide-windows/org/openide/windows/TopComponent.html[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.
[start=1]
1. In the Projects window, expand the ``Paint`` node, then expand the Source Packages node, and then right-click the ``org.netbeans.paint`` node. 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.
[start=2]
1. Near the top of the file, change the class declaration to the following:
[source,java]
----
public class PaintTopComponent extends TopComponent implements ActionListener, ChangeListener {
----
[start=3]
1. Press Ctrl-Shift-I to fix imports and click OK. The IDE makes the necessary import package declarations at the top of the file:
[source,java]
----
import java.awt.event.ActionListener;
import javax.swing.event.ChangeListener;
import org.openide.windows.TopComponent;
----
[start=4]
1. 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:
image::images/paintapp_lightbulb-60.png[]
Select Implement all abstract methods. The IDE generates two method skeletons— ``actionPerformed()`` and ``stateChanged()`` . You will fill these out later in this tutorial.
[start=5]
1. Register the ``PaintTopComponent`` in the window system by adding annotations to the top of the class, as shown here: link:http://bits.netbeans.org/dev/javadoc/org-openide-windows/org/openide/windows/TopComponent.Description.html[@TopComponent.Description]
[source,java]
----
(preferredID = "PaintTopComponent",
iconBase = "/org/netbeans/paint/new_icon.png", persistenceType = TopComponent.PERSISTENCE_ALWAYS)
link:http://bits.netbeans.org/dev/javadoc/org-openide-windows/org/openide/windows/TopComponent.Registration.html[@TopComponent.Registration](mode = "editor", openAtStartup = true)
link:http://bits.netbeans.org/dev/javadoc/org-openide-awt/org/openide/awt/ActionID.html[@ActionID](category = "Window", id = "org.netbeans.paint.PaintTopComponent")
link:http://bits.netbeans.org/dev/javadoc/org-openide-awt/org/openide/awt/ActionReferences.html[@ActionReferences]({
link:http://bits.netbeans.org/dev/javadoc/org-openide-awt/org/openide/awt/ActionReference.html[@ActionReference](path = "Menu/Window", position = 0),
link:http://bits.netbeans.org/dev/javadoc/org-openide-awt/org/openide/awt/ActionReference.html[@ActionReference](path = "Toolbars/File", position = 0)
})
link:http://bits.netbeans.org/dev/javadoc/org-openide-windows/org/openide/windows/TopComponent.OpenActionRegistration.html[@TopComponent.OpenActionRegistration](displayName = "#CTL_NewCanvasAction")
link:http://bits.netbeans.org/dev/javadoc/org-openide-util/org/openide/util/NbBundle.Messages.html[@Messages]({"CTL_NewCanvasAction=New Canvas"})
----
Notice that the ``PaintTopComponent`` will be displayed in the main area of the application, defined by the "editor" position. When the application starts, the window will be open. An action will be created for opening the window. The user will be able to invoke the action from a menu item and a toolbar button.
[start=6]
1. Add these two icons to "org/netbeans/paint":
image::images/paintapp_70_new_icon.png[]
image::images/paintapp_70_new_icon24.png[]
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.
[start=7]
1. Add the following variable declarations to the top of the ``PaintTopComponent`` class and then fix the import statements (Ctrl-Shift-I).
[source,java]
----
private 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 JSlider brushSizeSlider = new JSlider(1, 24); //A slider to set the brush 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(LBL_Clear()); //A button to clear the canvas
private final JLabel label = new JLabel(LBL_Foreground()); //A label for the color chooser
private final JLabel brushSizeLabel = new JLabel(LBL_BrushSize()); //A label for the brush size slider
private static int ct = 0; //A counter you use to provide names for new images
----
Change the link:http://bits.netbeans.org/dev/javadoc/org-openide-util/org/openide/util/NbBundle.Messages.html[@Messages] annotation at the top of the class to the following:
link:http://bits.netbeans.org/dev/javadoc/org-openide-util/org/openide/util/NbBundle.Messages.html[@Messages]
[source,java]
----
({
"CTL_NewCanvasAction=New Canvas",
"LBL_Clear=Clear",
"LBL_Foreground=Foreground",
"LBL_BrushSize=Brush Size"})
----
[start=8]
1. Define the constructor:
[source,java]
----
public PaintTopComponent() {
initComponents();
setDisplayName(UnsavedImageNameFormat(ct++));
}
----
Now change the link:http://bits.netbeans.org/dev/javadoc/org-openide-util/org/openide/util/NbBundle.Messages.html[@Messages] annotation at the top of the class to the following:
link:http://bits.netbeans.org/dev/javadoc/org-openide-util/org/openide/util/NbBundle.Messages.html[@Messages]
[source,java]
----
({
"CTL_NewCanvasAction=New Canvas",
"LBL_Clear=Clear",
"LBL_Foreground=Foreground",
"LBL_BrushSize=Brush Size",
"# {0} - image",
"UnsavedImageNameFormat=Image {0}"})
----
You have added an annotation that defines two keys in a bundle file that will be created when you build the module. The annotation specifies the text that will be used to identify a new image file in the application. For example, when a user clicks New Canvas for the first time in your completed application, a tab will appear above the Source Editor with the label, 'Image 0'.
[start=9]
1. Next, the first Java call you see above is to a method you haven't written yet, ``initComponents()`` , which will add a toolbar and a PaintCanvas to your ``TopComponent`` . Because you haven't written the method yet, a red line appears underneath it here. As before, click the light bulb (or press Alt-Enter) and accept the suggestion to let the IDE create the method for you.
[start=10]
1. Right-click the application and choose Run. The application starts up. Under the Window menu, choose New Canvas a few times and notice that you now have multiple canvases:
image::images/paintapp_70_run-app1.png[]
At this stage, you have created a window, and initialized a set of variables that you will need as you build the user interface of the application. You could use the Matisse GUI Builder for this but, as you will see in the next section, you can also simply use plain Java code.
=== Filling Out the Skeleton Methods
In this section, we code the user interface of our application. We could also use the IDE's GUI Builder to visually design the layout.
[start=1]
1. The ``initComponents()`` method installs components in your panel, so that the user has something to interact with. You generated its skeleton method during the previous section in the ``PaintTopComponent.java`` class. Fill it out as follows:
[source,java]
----
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);
toolbar.add(brushSizeLabel);
toolbar.add(brushSizeSlider);
toolbar.add(preview);
toolbar.add(clear);
}
----
Press Ctrl-Shift-I to generate the required import statements.
[start=2]
1. Fill out the other two methods that you generated. They are used for listening to the ``PaintTopComponent`` class:
[source,java]
----
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
canvas.clear();
} else if (e.getSource() instanceof ColorChooser) {
ColorChooser cc = (ColorChooser) e.getSource();
canvas.setColor(cc.getColor());
}
}
----
[source,java]
----
@Override
public void stateChanged(ChangeEvent e) {
canvas.setBrushDiameter(brushSizeSlider.getValue());
}
----
[start=3]
1. Check that the ``PaintTopComponent`` has this content:
[source,java]
----
package org.netbeans.paint;
import javax.swing.JButton;
import javax.swing.JLabel;
import net.java.dev.colorchooser.ColorChooser;
import javax.swing.JToolBar;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.TopComponent;
import static org.netbeans.paint.Bundle.*;
@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 {
private 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 JSlider brushSizeSlider = new JSlider(1, 24); //A slider to set the brush 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(LBL_Clear()); //A button to clear the canvas
private final JLabel label = new JLabel(LBL_Foreground()); //A label for the color chooser
private final JLabel brushSizeLabel = new JLabel(LBL_BrushSize()); //A label for the brush size slider
private static int ct = 0; //A counter you use to provide names for new images
public PaintTopComponent() {
initComponents();
setDisplayName(UnsavedImageNameFormat(ct++));
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
canvas.clear();
} else if (e.getSource() instanceof ColorChooser) {
ColorChooser cc = (ColorChooser) e.getSource();
canvas.setColor(cc.getColor());
}
}
@Override
public void stateChanged(ChangeEvent e) {
canvas.setBrushDiameter(brushSizeSlider.getValue());
}
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);
toolbar.add(brushSizeLabel);
toolbar.add(brushSizeSlider);
toolbar.add(preview);
toolbar.add(clear);
}
}
----
[start=4]
1. Run the application again and notice that you now have a functioning paint canvas:
image::images/paintapp_70_run-app2.png[]
That's it! You have completed the first part of the Paint Application. In the next part, you learn how to integrate with the NetBeans Platform's save functionality, which will enable the user to save images when changes have been made.
link:http://netbeans.apache.org/community/mailing-lists.html[Send Us Your Feedback]