当前页面: 开发资料首页 → Netbeans 专题 → 添加按钮的功能(初学者指南)(3)
摘要: 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.
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.