Given following code segment to calculate area of a rectangular, finish the impl
ID: 3827470 • Letter: G
Question
Given following code segment to calculate area of a rectangular, finish the implementation of button btnCol. You need to Calculate and display result properly, validate user's input (data should be positive), report error using label lblError, clear text fields after click button, move cursor to first text field./* Declare GUI components */private JLabel lblbLength new JLabel("Length: "); private JLabel lblWidth new JLabel("Width: "); private JLabel lblError new JLabel(""); private JTextField tfLength new = JTextField(10); private JTextField tfWidth new = JTextField(10); private JButton bfnCal = new JButton("Calculate"); private JTextArea taResult new = JTextArea(30, 20); private String strLength. strWidth. output; private double dbLength. dbWidth. area;/* Register button btnCal to action listener, finish button implementation. */btnCal.addActionListener(new ActionListener() {public void actionPerformed (ActionEvent e) {Explanation / Answer
Below is the method implementation with requirements. NUmber of lines can be reduced by moving repeated lines into separate method but this is more understandable and fits into the requirement of using single method.
Please give thumbs up or comment for queries
public void actionPerformed(ActionEvent e) {
dbLength = Double.parseDouble(lengthTF.getText());
dbWidth = Double.parseDouble(widthTF.getText());
strLength = String.valueOf(dbLength);
strWidth = String.valueOf(dbWidth);
if (dbLength < 0 && dbWidth < 0) {
lblError.setText(
"Length: " + strLength + " and Width: " + strWidth + " are negative, Enter positive values");
lblError.setVisible(true);
taResult.setText("");
lengthTF.setText("");
widthTF.setText("");
lengthTF.requestFocusInWindow();
} else if (dbLength < 0) {
lblError.setText("Length: " + strLength + " is negative, Enter positive value");
lblError.setVisible(true);
taResult.setText("");
lengthTF.setText("");
widthTF.setText("");
lengthTF.requestFocusInWindow();
} else if (dbWidth < 0) {
lblError.setText("Width: " + dbWidth + " is negative, Enter positive value");
lblError.setVisible(true);
taResult.setText("");
lengthTF.setText("");
widthTF.setText("");
lengthTF.requestFocusInWindow();
}
else {
area = dbLength * dbWidth;
output = String.valueOf(area);
taResult.setText(output);
lengthTF.setText("");
widthTF.setText("");
lengthTF.requestFocusInWindow();
lblError.setText("");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.