In this tutorial we will move away from the absolute exam objectives and have some fun building a graphical application in Java using the javax.swing classes. Netbeans IDE 7.4 comes with a simply brilliant GUI editor and we shall build the application in the free app that is available across many platforms. All the code will be build into the single application although with all OO apps we should consider splitting the back-end logic from the front end clients. This way we could easily have a command line and GUI client that reaches into the same back-end class. The app that we will build will convert temperatures from Centigrade to Fahrenheit and vice-versa.
First we will build the jFrame form to look something like this:
The NetBeans designer makes this task easy to align the components and takes just a little time. Don’t forget to add the radio buttons to a button group so only one can be selected at a time.
The code behind the Clear and Exit buttons is simple so we can add that in quickly. The Clear button will clear the text in the Temp and Result text fields:
txtTemp.setText(""); txtResult.setText("");
The Exit button will close the application:
System.exit(0);
The code the resides behind the Convert button needs to be a little more robust and is encapsulated in try and catch blocks. Firstly we check to see if at least one selection has been made in the radio buttons:
if (!(radC.isSelected()) && !(radF.isSelected())) { txtResult.setText("Select C or F"); }
With that underway the rest of the try block concerns itself to check which radio button is selected and runs the appropriate conversion:
try { double t = Double.parseDouble(txtTemp.getText()); double r; if (!(radC.isSelected()) && !(radF.isSelected())) { txtResult.setText("Select C or F"); } if (radC.isSelected()) { r = ((t * 9) / 5) + 32; String result = String.format("%.2f", r); txtResult.setText(result); } if (radF.isSelected()) { r = ((t - 32) * 5) / 9; String result = String.format("%.2f", r); txtResult.setText(result);
} }
The catch block will catch errors weher the user has not typed a number into the Temperature field and will then fail conversion from a String to Double:
catch (NumberFormatException e) { txtResult.setText("Must be a number"); }
The video is 30 minutes but well worth the investment of time: