blob: 64f1e55ae11dcdcfeba50aac24d15df839927fd4 [file] [log] [blame]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<!--
Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
-->
<head>
<title>Adding Functionality to Buttons: A Beginners Guide</title>
<meta name="description" content="Adding Functionality to Buttons with the NetBeans GUI Builder Matisse: This tutorial teaches you how to build a simple GUI with back-end functionality. This tutorial is geared to the beginner and introduces the basic construction of a GUI with functionality. We will work through the layout and design of a GUI and add a few Buttons and Text Boxes. The Text Boxes will be used for receiving user input and also for displaying the program output. The Button will initiate the functionality built into the front end.">
<link rel="stylesheet" href="../../netbeans.css">
<meta name="author" content="Saleem Gul, Tomas Pavek, Ruth Kusterer">
</head>
<body>
<h1>Adding Functionality to Buttons: A Beginners Guide</h1>
<div class="articledate" style="margin-left: 0px;">Contributed
by <a href="mailto:sguls2@hotmail.com">Saleem Gul</a> and Tomas Pavek, maintained by Ruth Kusterer</div>
<p>
This beginner tutorial teaches you how to build a simple GUI with back-end functionality.
You will learn how to develop a graphical user interface
and how to add functionality to the buttons and fields used.
A basic understanding of the Java Programming Language is required.
</p>
<p>
This document takes you through the fundamental concepts of GUI creation and
takes the approach taken in many self learning books. We will work through the
layout and design of a GUI and add a few Buttons and Text Boxes. The Text Boxes
will be used for receiving user input and also for displaying the program output.
The Button will initiate the functionality built into the front end.
The application we create will be a simple but functional calculator.
</p>
<p class="align-center"><B>Expected duration: 15 minutes</B></p>
<div class="indent">
<h3>Tutorial Exercises</h3>
<ul>
<li><A HREF="#Exercise_1">Exercise 1: Creating a Project</A></li>
<li><A HREF="#Exercise_2">Exercise 2: Building the Front End</A></li>
<li><A HREF="#Exercise_3">Exercise 3: Adding Functionality</A></li>
<li><A HREF="#Exercise_4">Exercise 4: Running the Program</A></li>
<li><A HREF="#how">How Event Handling Works</A></li>
<li><A HREF="#nextsteps">Next Steps</A></li>
</ul>
<h3>Prerequisites</h3>
<ul>
<li>The use should have basic skills in the Java language.
<li>The user should be comfortable with using the NetBeans IDE.
<li>The user should have already completed
the tutorial <A HREF="../60/java/quickstart-gui.html">GUI Building in Netbeans IDE 6.0</A>.
</ul>
<h3><a name="getting"></a>Software Needed for This Tutorial</h3>
<p>The NetBeans GUI Builder comes bundled with NetBeans IDE,
and no special setup is necessary.</p>
<p>Make sure you have the following software installed on your computer:</p>
<ul>
<li>NetBeans IDE 6.0 (<a href="https://netbeans.org/community/releases/60/index.html">download</a>)</li>
<li>In order to install and run NetBeans IDE 6.0, you also
require the Java SE Development Kit (JDK) version 5.0 or higher. You can get
a version of JDK for your platform at:
<a href="http://java.sun.com/javase/downloads/index.jsp">http://java.sun.com</a>.
</li>
</ul>
</div>
<p>
<h2><a name="Exercise_1"></a>Exercise 1: Creating a Project</h2>
<p>The first step is to create a Project, we will name our project NumberAddition.
<ol>
<p>
<LI>
<P>Choose File &gt; New Project. Alternately, you can click the New Project
icon in the IDE toolbar.</P>
<LI>
<P>In the Categories pane, select the General node. In the Projects pane,
choose Java Application. Click Next. </P>
<LI>
<P>Enter NumberAddition in the Project Name field and specify a path
e.g. in your home directory as the project
location. </P>
<LI>
<P>Ensure that the Set as Main Project checkbox is selected. Deselect Create
Main Class if it is selected. </P>
<LI>
<P>Click Finish.</P>
</ol>
<br />
<!-- ===================================================================================== -->
<h2><a name="Exercise_2"></a>Exercise 2: Building the Front End</h2>
<p>After creating the new application, you may have noticed that the Source Packages
folder in the Projects window contains an empty <code>&lt;default package&gt;</code>
node. To proceed with building our interface, we need to create a Java container
within which we will place the other required GUI components. In this step we'll
create a container using the <code>JFrame</code> component and place the container
in a new package.</p>
<div class="indent">
<h3 class="tutorial">Create a JFrame container</h3>
<ol>
<p>
<li>In the Projects window, right-click the NumberAddition node and choose
New &gt; JFrame Form.</li>
<p>
<li>Enter NumberAdditionUI as the Class Name.</li>
<p>
<li>Enter <code>my.NumberAddition</code> as the package. </li>
<p>
<li>Click Finish.</li>
</ol>
<p>The IDE creates the <code>NumberAdditionUI</code> form and the
<code>NumberAdditionUI</code> class within the <code>NumberAdditionUI.java</code>
application, and opens the <code>NumberAdditionUI</code> form in the
GUI Builder. Notice that the <code>my.NumberAddition</code>
package replaces the default package.</p>
<h3 class="tutorial">Adding Components: Making of the Front End</h3>
<p>
Next we are going to populate our application's front end with one JPanel,
and three JLabels, JTextFields and JButtons each.
The JFrame with the aforementioned components will look like this.
<p class="align-center"><img class="b-none" src="../../images_www/gui-functionality/Figure1.png" width="309" height="230"><br>
<p>Select Windows &gt; Palette to open the Palette if you don't see it.
You use the Palette to drag and drop UI components to the design area.
<ol>
<li>Start by selecting a JPanel from the Palette and drop it onto the JFrame.
<li>While the JPanel is highlighted, go to the Properties window
and click the &quot;...&quot; button next to Border to choose a border style.
<li>In the Border dialog, select Titled Border from the list,
and type in <code>Number Addition</code> in the Title field.
Click OK to save the changes and exit the dialog.
<li>You should now see an empty titled JFrame that says Number Addition
like in the screenshot. Look at the screenshot and add three
JLabels, three JTextFields and three JButtons as you see above.
</ol>
<h3 class="tutorial">Renaming the Components</h3>
<p>In this step we are going to rename the components that were just added to the
JFrame.</p>
<ol>
<li>Double-click on jLabel1 and change the text property to <code>First
Number</code></li>
<p>
<li>Double-click on jLabel2 and change the text to <code>Second Number</code></li>
<p>
<li>Double-click on jLabel3 and change the text to <code>Result</code> </li>
<p>
<li>Double-click on jTextField1 and remove the sample text in the text
field. You may have to resize the jTextField1 to its original size. Repeat
this step for jTextField2 and jTextField3. </li>
<P>
<LI> Double-click on jButton1 and rename it <code>Clear</code></P>
<P>
<LI> Double-click on jButton2 and rename it <code>Add</code></P>
<P>
<LI> Double-click on jButton3 and rename it <code>Exit</code></P>
</ol>
<p>Your Finished GUI should now look like this:</p>
<p class="align-center" class="tutorial"><img class="b-none" src="../../images_www/gui-functionality/Figure2.png" width="309" height="230"><BR>
</p>
</div>
<br />
<!-- ======================================================================================= -->
<h2><a name="Exercise_3"></a>Exercise 3: Adding Functionality</h2>
<p>In this exercise we are going to give functionality to the Add, Clear, and
Exit buttons. The jTextField1 and jTextField2 boxes will be used for user input
and jTextField3 for program output - what we are creating is a very simple calculator.
Let's begin.</p>
<div class="indent">
<h3 class="tutorial">Making the Exit Button Work</h3>
<p>In order to give function to the buttons, we have to assign an event
handler to each, responding to an event.
In our case we want to know when the button is pressed, either by mouse
click or via keyboard. So we will use ActionListener responding to ActionEvent.
<OL>
<LI><p>Right Click on the Exit button.
From the pop-up menu choose Events --&gt; Action --&gt; ActionPerformed.
Note that the menu contains many more events you can respond to!
When you select the actionPerformed event, the IDE will automatically
add an ActionListener to the Exit button and generate a handler method
for handling the listener's actionPerformed method.
<li>The IDE will open up the Source Code window and scroll to
where you implement the action
you want the button to do when the button is pressed (either by mouse
click or via keyboard).
Your Source Code window should contain the following lines:
<PRE class="examplecode">private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
<font color="#555555">//TODO: Add your handling code here:</font>
}</PRE>
<li>We
are now going to add code for what we want the Exit Button to do. You will have to type
System.exit(0); to the above code, replacing the TODO line.
Your finished Exit button code should look like this:
<PRE class="examplecode">private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
} </PRE>
</OL>
<h3 class="tutorial">Making the Clear Button Work</h3>
<p>
<ol>
<li>Click on the Design tab at the top of your work area to go back to the
Form Design</li>
<p>
<li>Right Click on the Clear button (jButton1). From the pop-up menu select
Events --&gt; Action --&gt; actionPerformed.
<p>
<li>We are going to have the Clear button erase all text from the jTextFields.
To do this, you will add some code like above. Your finished source code should look
like this: </p></li>
<PRE class="examplecode">private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
jTextField1.setText(&quot;&quot;);
jTextField2.setText(&quot;&quot;);
jTextField3.setText(&quot;&quot;);
}</PRE>
</ol>
The above code changes the text in all three
of our jTextFields to nothing, in essence it is overwriting the existing
Text with a blank.
<h3 class="tutorial">Making the Add Button Work</h3>
<p>The Add button will perform
three actions.
<ol><li>It is going to accept user input from jTextField1 and jTextField2 and
convert the input from a type String to a float. <li>It will then perform
addition of the two numbers and finally, <li>it will convert the sum to a type String
and place it in jTextField3.</ol>
Lets get started!
<OL>
<LI>Click on the Design tab at the top of your work area to go back to the
Form Design.</li>
<LI>Right-click on the Add button (jButton3). From the pop-up menu, select Events --&gt;
Action --&gt; actionPerformed</li>
<LI>We are going to add some code to have our Add button work. The
finished source code shall look like this:
<pre class="examplecode">private void jButton2ActionPerformed(java.awt.event.ActionEvent evt){
<font color="#555555">// First we define float variables.</font>
float num1, num2, result;
<font color="#555555">// We have to parse the text to a type float.</font>
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
<font color="#555555">// Now we can perform the addition.</font>
result = num1+num2;
<font color="#555555">// We will now pass the value of result to jTextField3.
// At the same time, we are going to
// change the value of result from a float to a string.</font>
jTextField3.setText(String.valueOf(result));
}</PRE>
</li>
</OL>
<p>Our Program is now complete we can now build and run it to see it in action. </p>
</div>
<P><!-- ===================================================================================== --><BR>
</P>
<h2><a name="Exercise_4"></a>Exercise 4: Running the Program</h2>
<p>The final step is to build and run the program.
<OL>
<LI>Click on Build in the Main Menu
and Choose --&gt; Build Main Project.</li>
<LI>When the Build output is finished,
click on Run in the Main Menu and Choose --&gt; Run Main Project
</li>
<LI>If you get a window informing you
that Project NumberAddition does not have a main class set, then
you should select my.NumberAddition.NumberAdditionUI as the main
class in the same window and click the OK button.</li>
<LI>Your created program is now running.</li>
</OL>
<p>In this tutorial you learned how you hook up functionality to
GUI components with the NetBeans GUI Builder Matisse.
<P><!-- ======================================================================================== --><BR>
</P>
<h2><a name="how"></a>How Event Handling Works</h2>
<p>This tutorial showed how to respond to a simple button event.
There are many more events you can have your application respond to. The IDE can help you find the
list of available events your GUI components can handle:
<ol>
<li><p>Go back to the file <code>NumberAdditionUI.java</code> in the Editor.
Click the Design tab to see the GUI's layout in the GUI Builder Matisse.
<li><p>Right-click any GUI component, and select Events from the pop-up menu.
For now, just browse the menu to see what's there, you don't need to select anything.
<li><p>Alternatively, you can select Properties from the Window menu. In the Properties window, click the Events tab.
In the Events tab, you can view and edit events handlers associated with the currently active GUI component.
<li><p>You can have your application respond to key presses, single,
double and triple mouse clicks, mouse motion, window size and focus changes.
You can generate event handlers for all of them from the Events menu.
The most common event you will use is an Action event.
(Learn <a href="http://java.sun.com/docs/books/tutorial/uiswing/events/generalrules.html#twokinds">best practices for Event handling</a> from Sun's <a href="http://java.sun.com/docs/books/tutorial/uiswing/events/index.html">Java Events Tutorial</a>.)
</ol>
<p>
How does event handling work? Everytime you select an event from the Event menu,
the IDE automatically creates a so-called event listener for you, and hooks it up to your component.
Go through the following steps to see how event handling works.
<ol>
<li><p>Go back to the file <code>NumberAdditionUI.java</code> in the Editor. Click the Source tab to see the GUI's source.
<li><p>Scroll down and note the methods <code>jButton1ActionPerformed()</code>,
<code>jButton2ActionPerformed()</code>, and <code>jButton3ActionPerformed()</code> that you just implemented.
These methods are called event handlers.
<li><p>Now scroll to a method called <code>initComponents()</code>. If you do not see this method,
look for a line that says <code>Generated Code</code>; click the + sign next to it
to expand the collapsed <code>initComponents()</code> method.
<li><p>First, note the blue block around the <code>initComponents()</code> method. This code was auto-generated
by the IDE and you cannot edit it.
<li><p>Now, browse through the <code>initComponents()</code> method. Among other things,
it contains the code that initializes and places your GUI components on the form.
This code is generated and updated automatically while you place and edit components in the Design view.
<li><p>In <code>initComponents()</code>, scroll down to where it says
<pre class="examplecode">jButton3.setText(&quot;Exit&quot;);
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});</pre>
This is the spot where an event listener object is added to the GUI component;
in this case, you register an ActionListener to the jButton3.
The ActionListener interface has an actionPerformed method taking ActionEvent
object which is implemented simply by calling your <code>jButton3ActionPerformed</code> event handler.
The button is now listening to action events. Everytime it is pressed an
ActionEvent is generated and passed to the listener's actionPerformed method
which in turn executes code that you provided in the event handler for this event.
</ol>
<p>
Generally speaking, to be able to respond, each interactive GUI component
needs to register to an event listener and needs to implement an event handler.
As you can see, NetBeans IDE handles hooking up the event listener for you, so you can concentrate
on implementing the actual business logic that should be triggered by the event.
</p>
<P><!-- ======================================================================================== --><BR>
</P>
<h2><a name="nextsteps"></a>Next Steps</h2>
<ul>
<li><a href="http://wiki.netbeans.org/wiki/view/NetBeansUserFAQ#section-NetBeansUserFAQ-GUIEditorMatisse">Matisse
GUI Builder - Frequently Asked Questions</a>
<li><a href="http://java.sun.com/docs/books/tutorial/uiswing/events/generalrules.html#twokinds">Best
practices for Event handling</a> from Sun's
<a href="http://java.sun.com/docs/books/tutorial/uiswing/events/index.html">Java Events Tutorial</a>.
<li><a href="https://netbeans.org/kb/60/java/gui-db.html">Building a Java Desktop Database Application</a>
<li>Code Samples can be found at <a href="http://javaalmanac.com/egs/java.awt.event/pkg.html">Java Almanac: Java Events</a>
</ul>
<div class="feedback-box"><a href="/about/contact_form.html?to=3&amp;subject=Feedback:Add%20Functionality%20to%20Buttons%20GUI%20Building%20Beginners%20Guide">Feedback</a>
</div>
<p>
If you have questions or need support,
and want to keep yourself informed on the latest
developments on the NetBeans IDE features,
join the <a href="mailto:nbusers@netbeans.org">nbusers@netbeans.org</a> mailing list by
sending an empty message to
<a href="mailto:nbusers-digest-subscribe@netbeans.org">nbusers-digest-subscribe@netbeans.org</a>.
</p>
</body>
</html>