In this part you will write the code for a temperature converter.
I will give you the imports free of charge:
1import java.awt.*; 2import java.awt.event.*; 3import javax.swing.*;
* means everything, so
java.awt.FlowLayout, etc. You will need these imports in all the other parts of this chapter as well. Also in this part I'll give you the first few lines of the class, and then I'll give the rest as pseudocode, which is just normal text that you have to translate into Java yourself:
1JTextField input = new JTextField(15); 2JButton btn = new JButton("Celsius to Farenheit"); 3JLabel label = new JLabel("No value converted", JLabel.CENTER);
Pseudocode for the
Instantiate, that is to say create, a new instance of the class.
Pseudocode for the constructor:
Add input, btn and label to the window. Set btn's action listener to this. Set layout to a new FlowLayout. Set size to (400, 85). Set title. Set it to be visible. Set default close operation to EXIT_ON_CLOSE.
Set celsiusValue to the value of input AS AN INTEGER. Set farenheitValue to ((celsiusValue * 9) / 5) + 32. Set the text of label to farenheitValue.
- To get the value of
input, use the
- You must remember to use
- To do a degree symbol in Java use
"\u00b0"- I know it is weird.
Modify the code to convert Farenheit to Celsius. You will have to add another button, and use
actionPerformed to check which button was pressed.
To do the final part you will have to use a
JOptionPane is essentially a class with lots of static methods of getting user input and displaying message. A
JOptionPane can be used as an alert box. Here is an example:
1JOptionPane.showMessageDialog(this, "This is a message"); 2// the first parameter is the frame to which the alert box belongs (or null if there isn't one) 3// the second parameter is the message
The final stage of the challenge is to show an alert box, using
JOptionPane, if the value entered is not an integer. You will need to use a try-catch block.
That was tough - but there is no rest for the wicked; or the programmer →