Created
June 19, 2018 20:32
-
-
Save irinaaZ/37eb6a8d5677ed0aa65c98a040e19b0c to your computer and use it in GitHub Desktop.
1. Write a temperature-conversion application that converts from Fahrenheit to Celsius. The Fahrenheit temperature should be entered from the keyboard (via a JTextField). A JLabel should be used to display the converted temperature.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package FahrenheitTask; | |
import javax.swing.*; | |
import java.awt.*; | |
import java.awt.event.ActionEvent; | |
import java.awt.event.ActionListener; | |
import java.text.DecimalFormat; | |
public class CelsiusFahrenheitConverter extends JFrame implements ActionListener { | |
private final JTextField jTextField; | |
private final JLabel result; | |
public CelsiusFahrenheitConverter() { | |
super("Fahrenheit to Celsius converter"); | |
setLayout(new FlowLayout()); | |
jTextField = new JTextField("enter the value of Fahrenheit", 20); | |
add(jTextField); | |
JButton button = new JButton("OK"); | |
button.addActionListener(this); | |
add(button); | |
result = new JLabel("Enter Fahrenheit value, and click OK"); | |
add(result); | |
} | |
public void actionPerformed(ActionEvent e) { | |
try { | |
DecimalFormat decimalFormat = new DecimalFormat("#.##"); | |
double inputFahrenheit = Double.parseDouble(jTextField.getText()); | |
double answer = 0.0; | |
answer = ((5.0 / 9.0) * (inputFahrenheit - 32.0)); | |
result.setText(String.valueOf(decimalFormat.format(answer))); | |
} catch (NumberFormatException ex) { | |
System.out.println("You have entered not a number, but illegal symbols or words, try again"); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package FahrenheitTask; | |
import javax.swing.*; | |
public class CelsiusFahrenheitConverterRunner { | |
public static void main(String[] args) { | |
CelsiusFahrenheitConverter celsiusFahrenheitConverter = new CelsiusFahrenheitConverter(); | |
celsiusFahrenheitConverter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
celsiusFahrenheitConverter.setSize(400, 250); | |
celsiusFahrenheitConverter.setVisible(true); | |
celsiusFahrenheitConverter.setLocationRelativeTo(null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment