当前页面: 开发资料首页 → Netbeans 专题 → Adding Functionality to Buttons: A Beginners Guide
摘要: 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. A basic understanding of the Java Programming Language is required.
This is a basic tutorial that takes the approach of teaching programming from the GUI development perspective.
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.
Expected duration: 15 minutes
Before you begin, you need to install the following software on your computer:
The first step is to create a Project, we will name our project NumberAddition.
Choose File > New Project. Alternately, you can click the New Project icon in the IDE toolbar.
In the Categories pane, select the General node. In the Projects pane, choose Java Application. Click Next.
Enter NumberAddition in the Project Name field and specify a path e.g. in your home directory as the project location.
Ensure that the Set as Main Project checkbox is selected. Deselect Create Main Class if it is selected.
Click Finish.
After creating the new application, you may have noticed that the Source Packages
folder in the Projects window contains an empty <default package>
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 JFrame
component and place the container
in a new package.
my.NumberAddition
as the package.
The IDE creates the NumberAdditionUI
form and the
NumberAdditionUI
class within the NumberAdditionUI.java
application, and opens the NumberAdditionUI
form in the
GUI Builder. Notice that the my.NumberAddition
package replaces the default package.
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.
Select Windows > 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.
Number Addition
in the Title field.
Click OK to save the changes and exit the dialog.
In this step we are going to rename the components that were just added to the JFrame.
First
Number
Second Number
Result
Clear
Add
Exit
Your Finished GUI should now look like this:
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.
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.
Right Click on the Exit button. From the pop-up menu choose Events --> Action --> 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.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { //TODO: Add your handling code here: }
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { System.exit(0); }
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){ jTextField1.setText(""); jTextField2.setText(""); jTextField3.setText(""); }
The Add button will perform three actions.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt){ // First we define float variables. float num1, num2, result; // We have to parse the text to a type float. num1 = Float.parseFloat(jTextField1.getText()); num2 = Float.parseFloat(jTextField2.getText()); // Now we can perform the addition. result = num1+num2; // 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. jTextField3.setText(String.valueOf(result)); }
Our Program is now complete we can now build and run it to see it in action.
The final step is to build and run the program.
In this tutorial you learned how you hook up functionality to GUI components with the NetBeans GUI Builder Matisse.
This tutorial showed how to respond to s 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:
Go back to the file NumberAdditionUI.java
in the Editor.
Click the Design tab to see the GUI's layout in the GUI Builder Matisse.
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.
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.
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 best practices for Event handling from Sun's Java Events Tutorial.)
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.
Go back to the file NumberAdditionUI.java
in the Editor. Click the Source tab to see the GUI's source.
Scroll down and note the methods jButton1ActionPerformed()
,
jButton2ActionPerformed()
, and jButton3ActionPerformed()
that you just implemented.
These methods are called event handlers.
Now scroll to a method called initComponents()
. If you do not see this method,
look for a line that says Generated Code
; click the + sign next to it
to expand the collapsed initComponents()
method.
First, note the blue block around the initComponents()
method. This code was auto-generated
by the IDE and you cannot edit it.
Now, browse through the initComponents()
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.
In initComponents()
, scroll down to where it says
jButton3.setText("Exit"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } });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
jButton3ActionPerformed
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.
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.