Reprint: How to run the GUI in NetBeans

Source: Internet
Author: User
Tags event listener gettext netbeans

This introductory tutorial will teach you how to create a simple human-computer interface and add simple back-office functionality to it. In particular, we'll show you how to write control buttons and field codes by Swing specification.

We will use the layout management, design a simple GUI interface, and add some buttons and text field components. The text field is used to receive input and display output, and the button is used in the front-end to start the corresponding function. The application we will create will be a simple but useful calculator.

For more GUI design features, videos and documentation, see Desgning a Swing gui in NetBeans IDE.

The software required for this tutorial

Make sure that your computer has the following software installed:

NetBeans IDE 6.0

Java Standard Development Kit (JDK) version 5.0 or 6.0

Step 1: Create the project

The first step is to create an application and name it numberaddition.

Choose File, New project. Or, click the new Item icon in the toolbar.

Select Java in the Categories pane of the Pop-up window, and in the Projects pane, select Java application. Click "Next";

Type numberaddition in the project name and type the local file directory in the project location to save the project;

The Confirm check box "set as Main project" is checked. And make sure that the check box "Create main class" is not checked.

Click "Finish"

Step 2: Build the interface

Continue to create our interface. We need a Java container to place other GUI components that will be called. In this step we use JFrame. Component as the desired container. We place the container in a new package, which is in the source package.

Create a JFrame. Container

Right-click Numberaddition in the Projects window and select New, JFrame. Form ".

In the class name entry, type Numberadditionui.

In the package item, type My.numberaddition.

Click Finish.

The IDE creates the Numberadditionui form in the Numberaddition application based on the class Numberadditionui and opens the Numberadditionui form in GUI Builder. Package My. Numberaddition is set as the default package.

Adding components: Building the interface

Next we will get a JPanel component for the interface through the palette. You will then add three jlabels components, three jtextfields components, and three jbuttons components to them. If you have never used GUI Builder, you should first get relevant information through the GUI Building in NetBeans IDE tutorial.

Once you have added the above components by dragging, JFrame. Should appear as follows:

If you do not see the palette in the upper-right corner of the IDE, select window, palette, to call out.

First select the JPanel component in the palette and drag it into the JFrame. In

When the JPanel component is highlighted, click the ellipsis (...) in its Properties window after the Border entry. button to select the component style.

Select the Titleborder style in the list of Border dialog boxes and fill in the number addition in the "title" entry. Click the OK button to save and exit.

You will now see an empty JFrame labeled number addition. Components, as described above. Please add three jlabels, three jtextfields and three jbuttons according to the above.

Renaming components

In this step we will rename just add into JFrame. The display text for the component

Double-click JLabel1 and change its text content to first number

Double-click JLabel2 and change its contents to Second number

Double-click JLabel3 and change its contents to Result

Double-click JTextField1 to delete its sample text. You need to readjust the initial size of the jTextField1. Also set JTextField2 and jTextField3.

Double-click JButton1, and Rename to Clear.

Double-click JButton2 and Rename to Add.

Double-click JButton3, and Rename to Exit.

The implementation GUI interface will be as follows:

Step 3: Add features

In this step, we will assign the function to the ADD, Clear, and Exit buttons. While JTextField1 and jTextField2 will be used for user input, JTEXTFIELD3 is used for program output-we will create a very simple addition calculator. Let's get started.

Let the Exit button work

In order to assign functionality to a button component, we must assign an event handler to each event that needs to be responded to. So we can know whether the user "pressed" the button, no LUN is through the mouse or keyboard operation. Therefore, we will use event listeners (ActionListener) to handle response events (ActionEvent).

Right-click the Exit button. Select "Event", "Action", "actionperformed" in the pop-up menu. Note that the menu contains many event handlers that you can use! When you select Actionperformed event handling, the IDE automatically adds an event listener (ActionListener) to the Exit button and generates a processing method within the listener's Actionperformed method.

The IDE goes to the source window and adjusts the cursor to the method in which you want to add functionality (when the mouse or keyboard action presses the button). As shown below:private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
   //TODO: Add your handling code here:
         }

Now we'll add the Exit button to the real code. You need to type System.exit (0); To overwrite the row where TODO is located. The following code:private void jButton3ActionPerformed (java.awt.event.ActionEvent evt) {
   System.exit(0);
         }

Let the Clear button work

Click the Design tab at the top of the workspace to return to the design interface.

Right-click the Clear button (jButton1). In the drop-down menu, select Event, Action, actionperformed.

We need the clear button to empty the text on all jtextfields. Add the code as you move up the next step. The completed code is as follows:private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
   jTextField1.setText("");
   jTextField2.setText("");
   jTextField3.setText("");
         }

The code above changes the text content of three jtextfields, placing the text in it empty.

Let the Add button work

The Add button will implement three functions.

Receives user input from JTextField1 and jTextField2 and converts the input string to floating-point data.

Add the two numbers from the above input to get the result.

Overwrites the result with the text in the jTextField3 to output the result.

Let's get started!

Click the Design tab above the workspace to return to the Design pane.

Right-click the Add button (JButton3). Select "Event", "Action", "actionperformed" in the pop-up menu

We'll add some code to make the Add button work. The code is as follows: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 project is complete and can now be built and run to see its functionality.

Step 4: Run the project

The final step is to build and run the project.

Select Build, build main project.

When the output pane displays successful build, choose Run, run main project.

If you are prompted to project numberaddition without setting the main class, you should select My. Numberaddition.numberadditionui as the main class and click on the "OK" button.

The project you created is now running successfully.

In this tutorial you learned how to correlate GUI components with NetBeans GUI Builder.

How Event handling Works

This tutorial shows you how to respond to a simple button event. There are, of course, more events that will allow your application to respond. The IDE helps you to easily find the event handling that your GUI component can implement in a list:

Let's return to the file Numberadditionui.java editor. Click on the "Design" tab to look back and forth in GUI Builder's GUI layout.

Right-click on any GUI component and select "Events" in the pop-up menu. Now, you don't need to select any options to navigate through the menu and see what features are available.

Alternatively, you can select Properties from the Window menu and click the Events tab in the Properties pane. In the Events tab, you can preview and edit the event handler to associate the current active component.

You can make your program respond such as carriage return, single-click, three-click, mouse activity, window size and focus changes and other operations. From the Events menu, you can automatically generate the appropriate event handler. There will be more event handling that you will be using. (See Best practices for Event handling from Sun Web page Java Events Tutorial.)

So, how does event handling work? Each time you select an event from the Events menu, the IDE automatically generates a so-called event listener for you and associates your component. Explore the following steps to understand how event handling works.

Return to the File Numberadditionui.java Editor and click on the "Source" tab to view the GUI source code.

Scroll through the code and note the Methods jbutton1actionperformed (), jbutton2actionperformed (), and jbutton3actionperformed (). These methods are implemented just now, called event handlers.

Now scroll the code to the Initcomponents () method. If you don't see this method, look for a line labeled Generated Code, and click the "+" sign in front of the line to expand the Initcomponents () method.

First, notice the blue undertone around the initcomponents () method. This indicates that the code is automatically generated by the IDE and is not allowed to be edited again.

Now, browse method Initcomponents (). In this code, you include code to initialize and set the location of your GUI components. These codes are automatically generated and configured when you set up and edit components in design mode.

Look for the following code in Initcomponents ()

jButton3.setText ("Exit");
jButton3.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) {
      jButton3ActionPerformed(evt);
   }
       });

This is where the GUI component adds event listeners, where you register an event listener (ActionListener) for JButton3. The method actionperformed in this ActionListener interface handles the response event by simply invoking the event handler jbutton3actionperformed that you previously set. Now this button will be able to monitor the event. When an event occurs, the system notifies the listener to execute the code in your event handler to respond to the event.

In general, to enable a GUI component to implement an event response requires registering the listener with the component and implementing event handling. As you can see, NetBeans IDE helps you automatically correlate event snooping, so you only have to focus on the logical relationships and internal connections between events and ignore implementation details.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.