Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that converts miles and kilometers as shown in the figure below.

ID: 3553488 • Letter: W

Question

Write a program that converts miles and kilometers as shown in the figure below. If you enter a value in the Mile text field and press the Enter key, the corresponding kilometer measurement is displayed in the Kilometer text field. Likewise, if you enter a value in the Kilometer text field and press the Enter key, the corresponding miles is displayed in the Mile text field.



If you are like me, you can't stand not having space around the edges of the labels and textfileds, in a earlier video, Prof Koets talked about the BorderFactory (Week 6 classroom video), this is a good place to test the class. It is really simple, just a couple of extra steps,

1st - import javax.swing.BorderFactory;

2nd - After you create your main paenl in the constructor, I will use the name mainPanel in my example, then call setBorder to set a width for your outside edges. I will use 20 pixels in the example:

   mainPanel.setBorder(BorderFactory.createEmptyBorder(20,20,20, 20));

3rd - you may have to adjust the size in the main I ended up setting the

    frame.setSize(250,125);

Testing the Program:

Run the program and resize the frame. Make sure the text boxes resize along with the labels next to them and nothing goes out of proportion. If it does, you need to rethink how you are packaging your objects inside the content panel of the JFrame. In other words, use a layout manager that keeps everything in the same location when the window is being resized, the text, labels, will not resize, but the textfields may resize depending on the layout you use.   For example, if you use a flow layout and then resize the window, everything changes position. It would be better to use a grid layout (for example) to keep things in 2 columns and 2 rows. When the window is resized everything will stay in the same relative position.

Click in a text box and enter a number. Press Enter. The answer should display in the other text box. Verify the accuracy of the numbers as you go in both directions.

I don't think you should need a UML with this one, only two classes MainFrame with inner class Listener and the Assign102 class which does the typical frame set up stuff.

Explanation / Answer

import java.io.*; import java.util.*; class MilesToKms{ public static void main (String[] args)throws Exception{ //1 mile = 1.609 344 kilometer; int miles Scanner scan= new Scanner (System.in); System.out.print("Enter a number of miles: "); float km = miles * 1.609344f; System.out.println(miles + " miles is " + km + " kilometers."); } }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote