jtf =
new JTextField("Enter the temperature", 13);//create the textfield to enter //temperature
jp.add(jtf);
jlTemperature =
new JLabel(" ",Label.
LEFT);//create the label to display the //textfield
jp.add(jlTemperature);
jf.add(jp);
jf.pack(); //setthe form of the JFrame
jf.setVisible(
true);// make visible JFrame
}
public void actionPerformed(ActionEvent ae ){
Stringchoice = ae.getActionCommand();
switch(choice){
case "Convertto Fahrenheit":
try{//checkthe entered text for wrong format(e.g.: “
abc” or “$, %”)
StringstringTextField = jtf.getText();//get the entered text
Doubled = Double.
parseDouble(stringTextField);// transfer to //number format for calculation
d= 9 * d / 5 + 32;// calculation
stringTextField= String.
valueOf(format.format("%.0f", d));//correctingthe result
jlTemperature.setText(stringTextField);
}
catch(NumberFormatException e){
jtf.setText("Enterthe temperature");//if the entered text has //wrong format
jlTemperature.setText("");
}
break;
case "Convertto Celsius":
StringstringTextField = jtf.getText();
try{
Doubled = Double.
parseDouble(stringTextField);
d= 5 * (d - 32) / 9;
stringTextField= String.
valueOf(format.format("%.0f", d));
jlTemperature.setText(stringTextField);
}
catch(NumberFormatException e){
jtf.setText("Enterthe temperature");
jlTemperature.setText("");
}
break;
case "Exit":
System.
exit(0);//if you select item “Exit”
}
}//method
}//class
Comments
Leave a comment