|
RHS |
Read Input 03
In this exercise we'll adapt our project "ReadInput02" a little and add some more calculations.
So start by creating the project "ReadInput03".
Also open the project "ReadInput02" and
copy the file "InputForm02" and rename (use Refactor) it to "InputForm03", then close "ReadInput02" again.
The content of the actionBtnActionPerformed() method is not doing the right thing so click "Source" and delete the content of the method.
First we'll make it possible to show some more output in a better way in
the window than we can now - a JLabel is not very suitable for several
lines of text.
So delete the "outputLbl" and
instead add a JTextArea, name it outputArea - to make it look good you probably need to extend your JFrame:
![]() |
Also we want to be able to choose other operations than add, so we'll add buttons for each operation - like a calculator. The buttons should be grouped together so we'll use a JPanel.
First delete the actionBtn and instead add a JPanel below the JTextArea - make it a little bigger so we can drop
some components on it, name it buttonPanel,
Click on the button to the right of the "border" property
and choose "BevelBorder"
Now add 5 JButtons to the panel, name them addBtn, subtractBtn, multiplyBtn,
divideBtn and clearOutputBtn.
Set their text attribute to "+", "-", "*", "/"
and "C" .
Finally change the headline to something more correct.
Resize and arrange so the frame looks something like
![]() |
As usual NetBeans can provide a method for each button that will be activated when the user clicks the button at runtime.
Select each button, one by one, right-click and choose Events -> Action -> actionPerformed and fill out the method with the appropiate code.
Below you find the code for the addBtn:
private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {
String s1 = n1Fld.getText();
String s2 = n2Fld.getText();
double n1 = Double.parseDouble(s1);
double n2 = Double.parseDouble(n2Fld.getText(s2));
String currentText = outputArea.getText();
String values = n1 + " + " + n2 + " = ";
double result = n1 + n2;
String newText = currentText + values + result + "\n";
outputArea.setText(newText);
}
Make sure you have analyzed the code until you are 100% sure that you understand it.
Add the code for the three next buttons eventhandling methods (subtractBtnActionPerformed(), multiplyBtnActionPerformed() and divideBtnActionPerformed()).
For the clearOutputBtn the code should clear the outputArea and the two textfields n1Fld and n2Fld - figure out yourself how to do that!
Compile (F9) - if you get any error: correct it and compile again.