CSC 103L - OOP Lab Manual (Java)
CSC 103L - OOP Lab Manual (Java)
CSC 103L - OOP Lab Manual (Java)
CSC 103L
OBJECT ORIENTED PROGRAMMING
(v. 1.1)
Student Name:
Class and
Section:
Roll Number:
CGPA:
Email ID:
PREPARED BY
Lab manual is prepared by Engr. Umar Mahmud under the supervision of Head of Department
Dr. M. Shaheen Khan in the year 2016. The manual was further revised by Dr. Shariq, Mr. M.
Ishtiaq and Mr. M. Fahad
GENERAL INSTRUCTIONS
a. Students are required to maintain the lab manual with them till the end of the semester.
b. All readings, answers to questions and illustrations must be solved on the place provided.
If more space is required then additional sheets may be attached.
c. It is the responsibility of the student to have the manual graded before deadlines as given
by the instructor
d. Loss of manual will result in re-submission of the complete manual.
e. Students are required to go through the experiment before coming to the lab session. Lab
session details will be given in training schedule.
f. Students must bring the manual in each lab.
g. Keep the manual neat clean and presentable.
h. Plagiarism is strictly forbidden. No credit will be given if a lab session is plagiarised and
no re submission will be entertained.
i. Marks will be deducted for late submission.
j. Error handling in a program is the responsibility of the Student.
VERSION HISTORY
5 INHERITANCE 10
6 OVERRIDING 10
7 ABSTRACTION 10
8 ENCAPSULATION 10
9 INTERFACES 10
10 JAVA PACKAGES 10
11 POLYMORPHISM 10
14 PAINT APPLICATION IN 10
NETBEANS
SESSIONAL TOTAL
PROJECT PHASE - I 10
PROJECT PHASE - II 20
PROJECT TOTAL 30
8. After downloading execute the software and be acquainted with its environment
(class activity)
9. A Java program is created as a Java Class. A Class is an abstract data type that has
attributes that describe the class as well as functions that allow the access and
manipulation of these attributes.
11. To create a Java class, remember that the file name should be same as the class
name. Also only one class can be created in a Java file.
12. Create a code in C++ that displays ‘Hello World’ (without quotes). Execute the (5)
code and show output here.
13. The following creates a Java class ‘MyFirstJavaProgram’ that has a function main.
The main function calls a utility in System class that displays the string ‘Hello
World’
The Java naming convention requires that the Class names should be without spaces
and the first letter of each word should be capitalized.
14. In Netbeans create a new file with name MyFirstJavaProgram. Type the code here (5)
and execute it. Display the output here.
15. What is the difference in the code written by you in Point 12 and the code provided (1)
in point 14?
17. String is a special construct that is an array of type char. A string is created in Java
as
String s = “OOP”;
18. Update the program in Point 13 and create a string variable of your name. Edit the (1)
program so that your name is printed. Show output and code here.
19. Arithmetic Expressions are a construct made up of variables and operators which
are constructed according to the syntax of the language that evaluates to a single
value.
20. Update the code in Point 19 that displays the result of the expression in Point 20. (1)
Show code and output here
22. Create a Java code that for numbers 2, 3 and 4 calculates the half of these numbers. (2)
Display the halves and write code and output here.
(b). x = 19
8. Strings: Strings, which are widely used in Java programming, are a sequence
of characters. In the Java programming language, strings are objects. The Java
platform provides the String class to create and manipulate strings. The most
direct way to create a string is to write:
9. Arrays: Java provides a data structure, the array, which stores a fixed-size
sequential collection of elements of the same type. An array is used to store a
collection of data, but it is often more useful to think of an array as a collection
of variables of the same type. Instead of declaring individual variables, such as
number0, number1, ..., and number99, you declare one array variable such as
numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. To use an array in a program, you must declare a variable
to reference the array, and you must specify the type of array the variable can
reference. Here is the syntax for declaring an array variable:
11. Loops: There may be a situation when we need to execute a block of code
several number of times, and is often referred to as a loop. Java has very flexible
three looping mechanisms. You can use one of the following three loops:
13 CSC 103L OOP – Control Structures and Loops
(a). while Loop
(b). do...while Loop
(c). for Loop
12. While Loop: Execute the following code and write the output. (.5)
13. Do While Loop: Execute the following code and write the output (.5)
14. For Loop: Execute the following code and write the output (.5)
17. Create a code that stores the first 10 prime numbers in an array. Then using (5)
arithmetic, in a loop of your choice, calculate the square and the cube of each
prime number and display appropriately. Show code and output here.
A method definition consists of a method header and a method body. Here are all
the parts of a method:
(a). Modifiers: The modifier, which is optional, tells the compiler how to call
the method. This defines the access type of the method.
(b). Return Type: A method may return a value. The returnValueType is the
data type of the value the method returns. Some methods perform the desired
operations without returning a value. In this case, the returnValueType is
the keyword void.
(c). Method Name: This is the actual name of the method. The method name
and the parameter list together constitute the method signature.
(d). Parameters: A parameter is like a placeholder. When a method is invoked,
you pass a value to the parameter. This value is referred to as actual
parameter or argument. The parameter list refers to the type, order, and
number of the parameters of a method. Parameters are optional; that is, a
method may contain no parameters.
(e). Method Body: The method body contains a collection of statements that
define what the method does.
6. In creating a method, you give a definition of what the method is to do. To use a
method, you have to call or invoke it. There are two ways to call a method; the choice
is based on whether the method returns a value or not. When a program calls a method,
17 CSC 103L OOP – Methods
program control is transferred to the called method. A called method returns control
to the caller when its return statement is executed or when its method-ending closing
brace is reached. If the method returns a value, a call to the method is usually treated
as a value. Execute the given code and write output here. Also trace the control flow
on the code using a pencil (1)
10 Write a function that receives an array and displays the contents of the array. Write
. the code and show the output here. Show the trace call on the code using a pencil.(2)
Web Resources:
http://www.tutorialspoint.com/java/java_methods.htm
Video Resources:
http://www.learnerstv.com/Free-Computers-Video-lectures-ltv006-Page1.htm
Summary: This lab is designed to create methods in Java. Students are given
exercise questions to practice method invocations and parameter passing for
different problems.
9. Compile and execute the following code. Show the output here (1)
Now based on the above example, In Object Oriented terms following are true:
(a). Animal is the superclass of Mammal class.
(b). Animal is the superclass of Reptile class.
(c). Mammal and Reptile are sub classes of Animal class.
(d). Dog is the subclass of both Mammal and Animal classes.
Now if we consider the IS-A relationship we can say:
(a). Mammal IS-A Animal
(b). Reptile IS-A Animal
(c). Dog IS-A Mammal
(d). Hence : Dog IS-A Animal as well
With use of the extends keyword the subclasses will be able to inherit all the properties
of the superclass except for the private properties of the superclass. We can assure that
Mammal is actually an Animal with the use of the instance operator.
7. Execute the following code and show output here. What happened in this code? (3)
This shows that class Van HAS-A Speed. By having a separate class for Speed we do not
have to put the entire code that belongs to speed inside the Van class., which makes it
possible to reuse the Speed class in multiple applications.
In Object Oriented feature the users do not need to bother about which object is doing the
real work. To achieve this, the Van class hides the implementation details from the users
of the Van class. SO basically what happens is the users would ask the Van class to do a
certain action and the Vann class will either do the work by itself or ask another class to
perform the action.
9. A very important fact to remember is that Java only supports only single inheritance. This
means that a class cannot extend more than one class. Therefore following is illegal:
However a class can implement one or more interfaces. This has made Java get rid of the
impossibility of multiple inheritance
10. Create a class Plants that has child classes of Trees and Shrubs. Create a Sub class of
Trees as Fruit bearing tress. Identify attributes and methods of each class. Instantiate the
fruit bearing tree class and show its attributes. Show the classes in the form of a tree as
well (7)
12. Repeat Point 11 with calling the overridden method of the grandparent class. Show (2)
code and output.
Web Resources:
http://www.tutorialspoint.com/java/java_overriding.htm
Video Lectures:
http://www.learnerstv.com/Free-Computers-Video-lectures-ltv006-Page1.htm
Summary: This lab is about method overriding in Java. Also use of super keyword
is also highlighted as used in Java.
9. Create an Abstract class student and create abstract methods. Create a class Fee to invoke
the abstract class. Show code and output here. Show the classes and methods graphically
as well. (8)
Web References:
http://www.tutorialspoint.com/java/java_encapsulation.htm
Video Lectures:
http://www.learnerstv.com/Free-Computers-Video-lectures-ltv006-Page1.htm
Summary: This lab introduces encapsulation concepts. Practice question provide a
mechanism to implement encapsulation.
10. Extending Multiple Interfaces: A Java class can only extend one parent class. Multiple
inheritances are not allowed. Interfaces are not classes, however, and an interface can
extend more than one parent interface. The extends keyword is used once, and the parent
interfaces are declared in a comma-separated list. For example, if the Hockey interface
extended both Sports and Event, it would be declared as:
Web Resources:
http://www.tutorialspoint.com/java/java_interfaces.htm
Video Links:
http://www.learnerstv.com/Free-Computers-Video-lectures-ltv006-Page1.htm
Summary: This lab identifies how interfaces are created used and extended. Interfaces
allow a developer to create a child class having multiple parents.
Execute the code and show output. What happened in this code? (1)
1. Objectives:
(a). Polymorphism
(b). Polymorphism in Java
2. Time Required: 3 hrs
3. Programming Language: Java
4. Software Required:
(a). Windows OS
(b). NetBeans / Eclipse Kepler
5. Polymorphism is the ability of an object to take on many forms. The most common use
of polymorphism in OOP occurs when a parent class reference is used to refer to a child
class object. Any java object that can pass more than one IS-A test is considered to be
polymorphic. In Java, all java objects are polymorphic since any object will pass the IS-
A test for their own type and for the class Object. It is important to know that the only
possible way to access an object is through a reference variable. A reference variable can
be of only one type. Once declared the type of a reference variable cannot be changed.
The reference variable can be reassigned to other objects provided that it is not declared
final. The type of the reference variable would determine the methods that it can invoke
on the object. A reference variable can refer to any object of its declared type or any
subtype of its declared type. A reference variable can be declared as a class or interface
type. Given the example
Now the Deer class is considered to be polymorphic since this has multiple inheritance.
Following are true for the above example:
(a). A Deer IS-A Animal
(b). A Deer IS-A Vegetarian
(c). A Deer IS-A Deer
(d). A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the following
declarations are legal:
Web Resources:
http://www.tutorialspoint.com/java/java_polymorphism.htm
Video Links:
http://www.learnerstv.com/Free-Computers-Video-lectures-ltv006-Page1.htm
Summary: This lab identifies how polymorphism is implemented in Java and its usage.
6. If you have worked with the NetBeans IDE in the past, much of this section
will look familiar, since the initial steps are similar for most projects. Still, the
following steps describe settings that are specific to this application, so take
care to follow them closely.
You may notice mention of "J2SE" in the description pane; that is the old name
for what is now known as the "Java SE" platform. Press the button labelled
"Next" to proceed.
Step 3: Set a Project Name
Make sure to deselect the "Create Main Class" checkbox; leaving this option
selected generates a new class as the main entry point for the application, but
our main GUI window (created in the next step) will serve that purpose, so
checking this box is not necessary. Click the "Finish" button when you are
done.
When the IDE finishes loading, you will see a screen similar to the above. All
panes will be empty except for the Projects pane in the upper left hand corner,
which shows the newly created project.
Now right-click the CelsiusConverterProject name and choose New -> JFrame
Form (JFrame is the Swing class responsible for the main frame for your
application.) You will learn how to designate this class as the application's
entry point later in this lesson.
Step 5: Name the GUI Class
Next, type CelsiusConverterGUI as the class name, and learn as the package
name. You can actually name this package anything you want, but here we are
following the tutorial convention of naming the package after the lesson in
which is resides.
When the IDE finishes loading, the right pane will display a design-time,
graphical view of the CelsiusConverterGUI. It is on this screen that you will
visually drag, drop, and manipulate the various Swing components.
7. It is not necessary to learn every feature of the NetBeans IDE before exploring
its GUI creation capabilities. In fact, the only features that you really need to
understand are the Palette, the Design Area, the Property Editor, and the
Inspector. We will discuss these features below.
The Palette
The Palette contains all of the components offered by the Swing API. You can
probably already guess what many of these components are for, even if this is
your first time using them (JLabel is a text label, JList is a drop-down list, etc.)
From this list, our application will use only JLabel (a basic text label),
JTextField (for the user to enter the temperature), and JButton (to convert the
temperature from Celsius to Fahrenheit.)
The Design Area
The Design Area is where you will visually construct your GUI. It has two
views: source view, and design view. Design view is the default, as shown
below. You can toggle between views at any time by clicking their respective
tabs.
A quick look at the source view reveals that the IDE has created a private
method named initComponents, which initializes the various components of
the GUI. It also tells the application to "exit on close", performs some layout-
specific tasks, then packs the (soon to be added) components together on
screen.
Don't feel that you need to understand this code in any detail; we mention it
here simply to explore the source tab. For more information about these
components, see:
The screenshot above shows the various properties of this object, such as
background color, foreground color, font, and cursor.
The Inspector
The last component of the NetBeans IDE that we will use in this lesson is the
Inspector:
The Inspector
The Inspector provides a graphical representation of your application's
components. We will use the Inspector only once, to change a few variable
names to something other than their defaults.
8. This section explains how to use the NetBeans IDE to create the application's
GUI. As you drag each component from the Palette to the Design Area, the
IDE auto-generates the appropriate source code.
Adding a JTextField
You may be tempted to erase the default text "JTextField1", but just leave it in
place for now. We will replace it later in this lesson as we make the final
adjustments to each component. For more information about this component,
see How to Use Text Fields.
Step 3: Add a JLabel
Next, drag a JLabel onto the Design Area. Place it to the right of the JTextField,
again watching for visual cues that suggest an appropriate amount of spacing.
Make sure that text base for this component is aligned with that of the
JTextField. The visual cues provided by the IDE should make this easy to
determine.
9. With the GUI components now in place, it is time to make the final
adjustments. There are a few different ways to do this; the order suggested here
is just one possible approach.
Step 1: Set the Component Text
First, double-click the JTextField and JButton to change the default text that
was inserted by the IDE. When you erase the text from the JTextField, it will
shrink in size as shown below. Change the text of the JButton from "JButton1"
to "Convert." Also change the top JLabel text to "Celsius" and the bottom to
"Fahrenheit."
The GUI portion of this application is now complete! If the NetBeans IDE has
done its job, you should feel that creating this GUI was a simple, if not trivial,
task. But take a minute to click on the source tab; you might be surprised at the
amount of code that has been generated.
To see the code in its entirety, scroll up and down within the IDE as necessary.
You can expand or collapse certain blocks of code (such as method bodies) by
clicking the + or - symbol on the left-hand side of the source editor.
The default names are not very relevant in the context of this application, so it
makes sense to change them from their defaults to something that is more
meaningful. Right-click each variable name and choose "Change variable
name." When you are finished, the variable names should appear as follows:
In the Design Area, click on the Convert button to select it. Make sure that only
the Convert button is selected (if the JFrame itself is also selected, this step
will not work.) Right-click the Convert button and choose Events -> Action -
> ActionPerformed. This will generate the required event-handling code,
leaving you with empty method bodies in which to add your own functionality:
There are many different event types representing the various kinds of actions
that an end-user can take (clicking the mouse triggers one type of event, typing
at the keyboard triggers another, moving the mouse yet another, and so on.)
Our application is only concerned with the ActionEvent; for more information
about event handling, see Writing Event Listeners.
Note:
This example is not localizable because the parseDouble method is not
localizable. This code snippet is for illustration purposes only. A more robust
implementation would use the Scanner class to parse the user input.
1. Objectives:
(a). Program exceptions
(b). Exception handling using Try Catch blocks
(c). Creating and handling own exceptions
2. Time Required: 3 hrs
3. Programming Language: Java
4. Software Required:
(a). Windows OS
(b). NetBeans / Eclipse Kepler
5. Exceptions: An exception is a problem that arises during the execution of a
program. An exception can occur for many different reasons, including the
following:
(a). A user has entered invalid data.
(b). A file that needs to be opened cannot be found.
(c). A network connection has been lost in the middle of communications or the
JVM has run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.
6. To understand how exception handling works in Java, you need to understand the
three categories of exceptions:
(a). Checked exceptions: A checked exception is an exception that is typically
a user error or a problem that cannot be foreseen by the programmer. For
example, if a file is to be opened, but the file cannot be found, an exception
occurs. These exceptions cannot simply be ignored at the time of
compilation.
(b). Runtime exceptions: A runtime exception is an exception that occurs that
probably could have been avoided by the programmer. As opposed to
checked exceptions, runtime exceptions are ignored at the time of
compilation.
(c). Errors: These are not exceptions at all, but problems that arise beyond the
control of the user or the programmer. Errors are typically ignored in your
code because you can rarely do anything about an error. For example, if a
stack overflow occurs, an error will arise. They are also ignored at the time
of compilation
7. Exception Hierarchy: All exception classes are subtypes of the
java.lang.Exception class. The exception class is a subclass of the Throwable class.
Other than the exception class there is another subclass called Error which is derived
from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally
happen in case of severe failures, which are not handled by the java programs. Errors
are generated to indicate errors generated by the runtime environment. Example:
JVM is out of Memory. Normally programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and
RuntimeException Class.
Here is a list of most common checked and unchecked Java's Built-in Exceptions.
A catch statement involves declaring the type of exception you are trying to catch.
If an exception occurs in protected code, the catch block (or blocks) that follows the
try is checked. If the type of exception that occurred is listed in a catch block, the
exception is passed to the catch block much as an argument is passed into a method
parameter.
The following is an array is declared with 2 elements. Then the code tries to access
the 3rd element of the array which throws an exception.
The previous statements demonstrate three catch blocks, but you can have any
number of them after a single try. If an exception occurs in the protected code, the
exception is thrown to the first catch block in the list. If the data type of the exception
thrown matches ExceptionType1, it gets caught there. If not, the exception passes
down to the second catch statement. This continues until the exception either is
caught or falls through all catches, in which case the current method stops execution
and the exception is thrown down to the previous method on the call stack.
Here is code segment showing how to use multiple try/catch statements.
A method can declare that it throws more than one exception, in which case the
exceptions are declared in a list separated by commas. For example, the following
method declares that it throws a RemoteException and an
InsufficientFundsException:
Web Resources:
http://www.tutorialspoint.com/java/java_exceptions.htm
http://www.tutorialspoint.com/java/java_builtin_exceptions.htm
Video Links:
http://www.youtube.com/watch?v=4my7mKFaNQs
http://www.youtube.com/watch?v=LpfHEjEoDCg
http://www.youtube.com/watch?v=K_-3OLkXkzY
Summary: This lab identifies how exceptions are handled in Java. Exceptions are
classes that allow the developers to identify alternate program flow. Students are
given an opportunity to create their own exceptions and show them using traces.
1. Objectives:
(a). Creating a Paint application in NetBeans
(b). Creating and embedding canvas in a paint window
(c). Running, branding and packaging the project
2. Time Required: 3 hrs
3. Programming Language: Java
4. Software Required:
(a). Windows OS
(b). NetBeans
5. Paint Application:
You will create a simple application on the NetBeans Platform. The application allows
the user to paint on the screen:
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.
6. 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.
(b). In the Name and Location panel, type PaintApp in Project Name. Change the
Project Location to any directory on your computer. Click Finish.
(c). The new application skeleton opens in the IDE. Look at the new project
structure:
(d). You see two sub nodes in the Projects window. The first sub node, 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 sub node 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.
(f). 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.
7. Creating the Functionality Module: Now you need a module to contain the actual
code you're going to write.
(a). Right-click the "Modules" node in the Paint Application. Select Add New:
(b). In the Name and Location panel, type Paint in Project Name. Notice that the
module sources will be stored within a folder in the application's directory on
disk. Click Next.
(d). 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:
Window
Gives you access to the NetBeans window
TopComponent System
system.
API
(f). 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
(h). 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.
8. 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.
(a). 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.
(b). 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.
(c). Replace the default content of the file with the content found below. If you named
your package something other than org.netbeans.paint, correct the package name
in the Source editor. Content is available here:
https://platform.netbeans.org/images/tutorials/paintapp/70/PaintCanvas.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
/**
*
* @author Tim Boudreau
*/
public class PaintCanvas extends JComponent {
private int brushDiameter = 10;
private final MouseL mouseListener = new MouseL();
private BufferedImage backingImage = null;
private final BrushSizeView brushView = new BrushSizeView();
private Color color = Color.BLUE;
public PaintCanvas() {
addMouseListener(mouseListener);
addMouseMotionListener(mouseListener);
setBackground(Color.WHITE);
setFocusable(true);
}
@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawRenderedImage(getImage(), AffineTransform.getTranslateInstance(0,
0));
}
JComponent getBrushSizeView() {
return brushView;
}
@Override
public Dimension getPreferredSize() {
return new Dimension (24, 24);
}
}
@Override
public void mouseDragged(MouseEvent e) {
mouseClicked(e);
}
}
}
9. 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.
(c). 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;
(d). 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:
(e). Select Implement all abstract methods. The IDE generates two method
skeletons—actionPerformed() and stateChanged(). You will fill these out later in
this tutorial.
(f). 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",
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.
11. Write the following code in PaintTopComponent class
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 ColorComboBox color = new ColorComboBox(); //Our color
chooser component from the ColorChooser library
private final JButton clear = new JButton(Bundle.LBL_Clear()); //A button to
clear the canvas
private final JLabel label = new JLabel(Bundle.LBL_Foreground()); //A label for
the color chooser
private final JLabel brushSizeLabel = new JLabel(Bundle.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(Bundle.UnsavedImageNameFormat(ct++));
}
setLayout(new BorderLayout());
(c). Use the application and try to identify areas where you'd like to provide more
functionality.
15. Branding the Application:
(a). Right-click the application and choose Branding.
(b). Choose the distribution mechanism relevant to your business needs and your user
requirements.
(c). Switch to the Files window (Ctrl-2) to see the result.
17. Include following functionalities in the paint project: - (10)
(a). Eraser
(b). Line, rectangle and circle drawing mechanism
(c). Fill tool
Confucius
Marie Curie