Write an applet and design an interface which will accept miles and convert to kilometers and display the result when calculate button is pressed. Pls write code in java
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
//DistanceConverter.java (applet)
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class DistanceConverter extends JApplet implements ActionListener {
// declaring important components
private JTextField milesInput;
private JTextField kmOutput;
// this method gets called only once, at the start
@Override
public void init() {
// using a grid layout with 3 rows and 2 columns
setLayout(new GridLayout(3, 2));
// initializing text fields and convert button
milesInput = new JTextField(10);
kmOutput = new JTextField(10);
kmOutput.setEditable(false); // not editable
JButton convert = new JButton("Convert");
// adding each label and text field and button to the applet window
add(new JLabel("Input distance in miles: "));
add(milesInput);
add(new JLabel("Distance in kilometers: "));
add(kmOutput);
add(convert);
// using 300x100 size
setSize(300, 100);
// adding action listener to convert button
convert.addActionListener(this);
}
// this method gets invoked when convert button is pressed
@Override
public void actionPerformed(ActionEvent e) {
// fetching miles from milesInput as double
double miles = Double.parseDouble(milesInput.getText());
// converting miles to km and displaying in kmOutput textfield
double km = miles * 1.609344;
kmOutput.setText("" + km);
}
}
/*OUTPUT*/
Get Answers For Free
Most questions answered within 1 hours.