Design a Swing GUI formula calculator Your program will prom
Design a Swing GUI formula calculator. Your program will prompt the user to enter a non-negative number. If the user enters a negative number or a nondigit number, throw and handle an appropriate exception and prompt the user to re-enter another number. Your calculator has a button labeled “display result”; if it is clicked the system will display the result of calculation based on the following formula.
Solution
Java Program:
/* Java Program that generates formula calculator GUI */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.Math;
//Class definition
public class FormulaCalculator
{
private JFrame mainFrame;
private JPanel controlPanel;
//Constructor
public FormulaCalculator()
{
//Preparing window
prepareUI();
}
//Main method
public static void main(String[] args)
{
FormulaCalculator formulaCalculator = new FormulaCalculator();
formulaCalculator.showTextField();
}
//Creating a window
private void prepareUI()
{
//Adding label to frame
mainFrame = new JFrame(\"Simple UI\");
mainFrame.setSize(800,200);
mainFrame.setLayout(new GridLayout(3, 1));
//Adding window listener
mainFrame.addWindowListener(new WindowAdapter()
{
//Window close event
public void windowClosing(WindowEvent windowEvent)
{
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(controlPanel);
mainFrame.setVisible(true);
}
//Adding controls to frame
private void showTextField()
{
//Adding label\'s
JLabel numlabel= new JLabel(\"Enter a number: \", JLabel.RIGHT);
JLabel resLabel = new JLabel(\" Result: \", JLabel.CENTER);
//Adding text fields
final JTextField numText = new JTextField(6);
final JTextField resText = new JTextField(6);
//Making total text field non editable
resText.setEditable(false);
//Calculate button
JButton calcButton = new JButton(\"Display Result\");
//Button event action listener
calcButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Calculating formula
double result, x;
//Handling exceptions
try
{
//Reading x value
x = Double.parseDouble(numText.getText());
//If x is a negative number
if(x < 0)
{
//Throws exception
throw new Exception(\"\");
}
//Calculating numerator of formula
result = (-1 * x) + Math.sqrt( ( Math.abs( (x*x) - (4*x) +2 ) ) );
//Calculating total formula
result = result / 2.0;
//Assigning result to text
resText.setText(String.format( \"%.2f\", result ));
}
catch(Exception ex)
{
//Displaying error message
JOptionPane.showMessageDialog(null, \"Please enter a non-negative number\");
numText.setText(\"\");
}
}
});
//Adding controls to frame
controlPanel.add(numlabel);
controlPanel.add(numText);
controlPanel.add(resLabel);
controlPanel.add(resText);
//Adding button
controlPanel.add(calcButton);
mainFrame.setVisible(true);
}
}


