Question
Homework 16 - JButtons & TextFields How much is that doggie in the window, really? When it comes to buying on time, sometimes it's really
Homework 16 - JButtons & TextFields
How much is that "doggie" in the window, really? When it comes to buying "on time", sometimes it's really hard to get the information you need. Suppose you want to buy a new $3,500 computer system. Should you use your credit card, or finance it through the store? How much will your monthly payments be? How much lower will your payments be if you finance it over 3 years instead of 2? Here's a Java application that can give you some answers. |
Step-By-Step Instructions
Step 1
Create a class called HowMuch that is extended from JFrame. Make sure you have created a constructor that opens your application, sets it's size and default close operation, and makes it visible. The size used in the example above is 350 x 300.
Step 2
Import the required packages. Add the necessary import statements to ensure that you can use JButtonsand JLabels, as well as the import statement necessary to respond to events, and the import statement necessary to format numeric output.
Step 3
Define the components of the applications field. Add the necessary JTextField, JButton, and JLabelobject attributes to your class.
Create a Container called content that is intialized by sending the getContentPane message to the current object.
You'll need a separate JTextField for the user to enter the borrowed amount; another where the user can enter the yearly interest rate, and a third where the user can enter the number of years to finance the purchase. Hint: I usually name my user-interface fields with a prefix that identifies the kind of object it is. In this case, for instance, I'd give the purchase amount object the name, tfAmount, where the tf stands for TextField
You'll need two JLabel fields to display the output from your program. One JLabel will display the monthly payment [lblPayment ], and one JLabel will display the total cost of your purchase [lblTotCost], including interest.
You'll need one JButton field. When the user of your application presses the JButton you'll retrieve the values they've entered into the JTextFields, calculate the payment and total cost for the purchase and display the nicely formatted data in your two JLabel fields.
Step 4
Initialize your application. Inside your constructor, you must add each of your object attributes to the surface of the content pane so that the user can see them and interact with them. You should also create some additionalJLabel objects to identify each of the input and ouput components.
Start by setting the layout of the content pane to a GridLayout that is 0 rows, 2 columns, 5 pixel vgap, and 5 pixel hgap
Add the components and their JLabels one by one:
Inside the constructor, create a local descriptive JLabel that contains the text "Amount Borrowed". Make sure the JLabel is aligned to the right. [This requires you to use a 2-argument JLabelconstructor].
Add the descriptive JLabel to the content pane, using the add() method on the Container called content. On the following line, add the amount borrowed text field to the content pane as well.
Repeat the same steps--create a local, descriptive JLabel and then add the JLabel field and its associated component to the content pane for each of the remaining fields. You can see the suggested text for each component by examining the image at the top of this page.
Finally, add your JButton object to the content pane after all of the other components have been added.
Step 5
Hook up the event system. Even though your application has a JButton, it will not notify your application when it is clicked unless you tell it to. Here's how:
You "activate" your JButton object by sending it the addActionListener() message and passing along the name this as an argument. (You are, in effect, telling your JButton object to notify your application [this ] when it is clicked.) This code must go inside the constructor. Put it after the line that adds the JButton to the content pane.
JButton objects are only willing to send event notifications to "specially marked" applications. To tell Java that your application is willing and able to accept such notification, add the phrase implements ActionListener to the end of your application's class header.
Step 6
Get input from the user. Once activated, your application's JButton will look for a method namedactionPerformed() whenever it is clicked. Every application that implements ActionListener must include a method named actionPerformed() to handle those requests. You can see an example of this in the lecture material on JButtons and events.
Inside the actionPerformed() method you have to calculate the cost of your loan. The first step in calculating the cost of a loan is to retrieve the information about the amount borrowed, the yearly interest rate, and the term of the loan.
Here's how you do that: [Add this code inside the actionPerformed() method.]
Create three local String variables, one to hold the text stored in each of your JTextField objects.
Send each JTextField object a getText() message. When it receives that message it will return the text that it contains. Save the text returned by getText() in your String variables by using the assignment operator.
Step 7
Convert the input. The input entered by the user is in textual form. Before you can do calculations however, you need to convert it to binary form. Because the HowMuch application deals with fractional numbers you should convert each entry to a double value.
Here are the steps required to convert a String like "123.45" into a floating point double value. For more in-depth information, make sure you read Learning Unit 8B, "Data-In & Data Out".
Create a local Double object for each of the String variables extracted in Step 5. Construct your Double objects by passing each String to the appropriate constructor, like this:
Double amountDbl = new Double(amountStr);
where amountStr is one of the String variables initialized in Step 5. [Note that a Double variable is different than a double [little d] variable. A Double variable is an object, but it can't be used for arithmetic. A double variable is a primitive value.]
Create a primitive double local variable to match each of the Double objects created in the previous step. Initialize your double variables by sending your Double objects the doubleValue() message, like this:
double amount = amountDbl.doubleValue();
Step 8
Perform the calculations. Now that you've retreived the information from the user you'll need to manipulate that information to calculate the answers required by the problem.
Here's what you need to know to perform your calculations:
The formula to calculate a payment when the loan amount, interest rate, and term are all known is:
loan amount x interest rate payment = ____________________________________ 1 - (1 / (1 + interest rate))term * 12
When you perform your calculations you can use two of the numbers you obtained in the previous step--loan amount and loan term--without any further processing.
You need to modify the interest rate variable, however, before you can use it because the user expects a monthly rate and the user entered a yearly rate. In addition, the rate entered by the user needs to be converted to a decimal percentage.
Here's what you need to do:
Since the user entered the interest rate as 7.5, rather than .075, the first step is to divide the interest rate by 100 and store the result back in the interest rate variable. This is the actual yearly interest rate.
The formula above however, requires a monthly interest rate not a yearly one. Divide the interest rate calculated in the previous step, this time by 12, and store the result back in your interest rate variable.
Once the interest rate is squared away create a new double variable called payment and plug the rest of the variables into the formula shown above storing the result in payment. Since Java doesn't have an exponentiation operator you'll have to use the Math.pow() method to calculate the "bottom" part of the interest calculation like this:
(1 - (Math.pow(1/(1+rate), term * 12)))
Step 9
Display the output. To display the output send the setText() message to the JLabel objects you created in Step 3. One complication is that you have to convert your new binary answers back into Strings before they can be displayed.
Here's a summary of how to do that.
Create a new local NumberFormat object using the getCurrencyInstance() method.
Send your NumberFormat object the format() message. Pass the number you want formatted as an argument.
Save the formatted String obtained by calling the () method, and pass it to the appropriate setText() method.
Format the variable [computed in Step 8] for the first output label. For the total cost label, simply multiply the monthly payment by 12 and then multiply the result by the term to find the total cost.
First GUI App Amount Of Purchase 3500 Interest Rate like 7.5] Years To Pay 5 Monthly Payment $70.13 Total Purchase Cost $4,207.97 CalculateStep by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started