I was searching for a way to exercise the Java 8 concepts I've been learning, especially pertaining to Lambdas. Incidentally, I hadn't used any swing in a while and wanted a refresher. This is the result of these two pursuits.
import java.awt.GridLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class EquationCalculator {
static interface Equation {
double compute(double val1, double val2);
}
public static void main(String[] args) {
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(() -> new EquationCalculator());
}
public EquationCalculator() {
JFrame frame = new JFrame("Basic Operations");
JPanel panel = new JPanel(new GridLayout(1, 3));
JTextField first = new JTextField("2");
JTextField second = new JTextField("3");
JComboBox<String> calculate = new JComboBox<>();
calculate.addItem("Sum");
calculate.addItem("Difference");
calculate.addItem("Product");
calculate.addItem("Quotient");
calculate.addItem("Exponent");
calculate.addActionListener(
e -> JOptionPane.showMessageDialog(
null, "The result is " +
calculate(
String.valueOf(calculate.getSelectedItem()),
Double.parseDouble(first.getText()),
Double.parseDouble(second.getText())
),
"Result", JOptionPane.INFORMATION_MESSAGE
)
);
panel.add(first);
panel.add(second);
panel.add(calculate);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static double calculate(String operation, double val1, double val2) {
Equation add = (alpha, beta) -> alpha + beta;
Equation subtract = (alpha, beta) -> alpha - beta;
Equation multiply = (alpha, beta) -> alpha * beta;
Equation divide = (alpha, beta) -> alpha / beta;
Equation exponentiate = (alpha, beta) -> Math.pow(alpha, beta);
switch(operation) {
case "Sum":
return add.compute(val1, val2);
case "Difference":
return subtract.compute(val1, val2);
case "Product":
return multiply.compute(val1, val2);
case "Exponent":
return exponentiate.compute(val1, val2);
}
return divide.compute(val1, val2);
}
}
I recognize it's simple, and I can imagine there's likely a bit of "learned how to use a hammer...everything looks like a nail" going on, but I'd nonetheless appreciate any pinpointing good design choices vs poor ones and where I could improve.