Java Calculator Assistance - java

This is my 1st post here and I am hoping if I could get some help on a school project I have. The project is to make a calculator in Java and I have made it and it works fine for the most part, only problem I am having is that when I get an answer - lets say 5+5=10 and 10 is displayed, when I want to enter another number lets say I want to enter in 8*10 and in order to do that I write in 8, instead of deleting the previous answer which is 10 and write 8 instead of that number it will write 8 after 10, so it will be 108. What I want is for the previous answer to be deleted once I enter in a new number after an answer has been give. I hope I explained it good, here is my code and I would love some assistance on the matter since everything I tried hasn't worked. Thanks in advance.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator_UI implements ActionListener {
JFrame frame = new JFrame("Calculator");
JPanel panel = new JPanel();
JTextArea text = new JTextArea(1, 20);
JButton but1 = new JButton("1");
JButton but2 = new JButton("2");
JButton but3 = new JButton("3");
JButton but4 = new JButton("4");
JButton but5 = new JButton("5");
JButton but6 = new JButton("6");
JButton but7 = new JButton("7");
JButton but8 = new JButton("8");
JButton but9 = new JButton("9");
JButton but0 = new JButton("0");
JButton butadd = new JButton("+");
JButton butsub = new JButton("-");
JButton butmulti = new JButton("*");
JButton butdiv = new JButton("/");
JButton buteq = new JButton("=");
JButton butclear = new JButton("C");
Double number1, number2, result;
int addc = 0, subc = 0, multic = 0, divc = 0;
public void ui() {
frame.setVisible(true);
frame.setSize(230, 200);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
panel.add(text);
panel.add(but1);
panel.add(but2);
panel.add(but3);
panel.add(but4);
panel.add(but5);
panel.add(but6);
panel.add(but7);
panel.add(but8);
panel.add(but9);
panel.add(but0);
panel.add(butadd);
panel.add(butsub);
panel.add(butmulti);
panel.add(butdiv);
panel.add(buteq);
panel.add(butclear);
but1.addActionListener(this);
but1.setBackground(Color.cyan);
but2.addActionListener(this);
but2.setBackground(Color.cyan);
but3.addActionListener(this);
but3.setBackground(Color.cyan);
but4.addActionListener(this);
but4.setBackground(Color.cyan);
but5.addActionListener(this);
but5.setBackground(Color.cyan);
but6.addActionListener(this);
but6.setBackground(Color.cyan);
but7.addActionListener(this);
but7.setBackground(Color.cyan);
but8.addActionListener(this);
but8.setBackground(Color.cyan);
but9.addActionListener(this);
but9.setBackground(Color.cyan);
but0.addActionListener(this);
but0.setBackground(Color.cyan);
butadd.addActionListener(this);
butadd.setBackground(Color.cyan);
butsub.addActionListener(this);
butsub.setBackground(Color.cyan);
butmulti.addActionListener(this);
butmulti.setBackground(Color.cyan);
butdiv.addActionListener(this);
butdiv.setBackground(Color.cyan);
buteq.addActionListener(this);
buteq.setBackground(Color.cyan);
butclear.addActionListener(this);
butclear.setBackground(Color.cyan);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == butclear) {
number1 = 0.0;
number2 = 0.0;
text.setText("");
}
if (source == but1) {
text.append("1");
}
if (source == but2) {
text.append("2");
}
if (source == but3) {
text.append("3");
}
if (source == but4) {
text.append("4");
}
if (source == but5) {
text.append("5");
}
if (source == but6) {
text.append("6");
}
if (source == but7) {
text.append("7");
}
if (source == but8) {
text.append("8");
}
if (source == but9) {
text.append("9");
}
if (source == but0) {
text.append("0");
}
if (source == butadd) {
number1 = number_reader();
text.setText("");
addc = 1;
subc = 0;
multic = 0;
divc = 0;
}
if (source == butsub) {
number1 = number_reader();
text.setText("");
addc = 0;
subc = 1;
multic = 0;
divc = 0;
}
if (source == butmulti) {
number1 = number_reader();
text.setText("");
addc = 0;
subc = 0;
multic = 1;
divc = 0;
}
if (source == butdiv) {
number1 = number_reader();
text.setText("");
addc = 0;
subc = 0;
multic = 0;
divc = 1;
}
if (source == buteq) {
number2 = number_reader();
if (addc == 1) {
result = number1 + number2;
text.setText(Double.toString(result));
}
if (subc == 1) {
result = number1 - number2;
text.setText(Double.toString(result));
}
if (multic == 1) {
result = number1 * number2;
text.setText(Double.toString(result));
}
if (divc == 1) {
result = number1 / number2;
text.setText(Double.toString(result));
}
}
}
public double number_reader() {
Double num1;
String s;
s = text.getText();
num1 = Double.valueOf(s);
return num1;
}
}

When the user presses = and the result is printed, you should set a flag to true, so that the next time a number button is pressed, the result is first erased.
In fact you should even transform your whole logic into a state diagram, because if, for example, the user presses + twice, you should probably display an error message or ignore the second +, instead of reading the current number. Each state should define what happens when any button is pressed, and what the next state is depending on which button is pressed.
Since a GUI can be smarter than a real calculator, each state could also define which buttons are enabled and which ones are disabled.

Related

How can I organize my Java code?

The title is not my entire question. I know HOW to organize code, theoretically, but i would like some specific, USEFUL, pointers. Please read on before griping.
I'm a beginner to java and OOP (object oriented programming) and I would really like to learn how to better organize my code! Over the course of a month or two, I made a calculator program with little functions I thought of here and there with a few small jokes built into it. After looking at it a second time I realized that it is extremely poorly formatted and almost incomprehensible.If I may, I would like to ask some more experienced programmers to point me in the right direction on what I should do to fix it (for example, what things can I turn into objects, Where can I compartmentalize, etc).
Please note that this is my FIRST time posting on a forum like this so if i need to clarify something for you to help me, I've done something wrong, I'm asking for too much, please tell me so i can resolve it and i can get help. Please dont just mark this as invalid and file it away to oblivion (as often happens in stackoverflow). Also, before anyone asks, NO this is NOT homework, it is the product of my own crack at teaching myself java (probably why its not working too well).
Here is the source code:
// This is the original Calculator code without objects in a single class. not really efficient...
package randomClasses;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;
#SuppressWarnings("serial")
public class CalcClass
extends JFrame
implements ActionListener {
JPanel[] row = new JPanel[6];
JButton[] button = new JButton[21];
String[] buttonString = {"7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", ".", "/", "C", "v", "+/-", "=", "0", "Parabola", "x^y"};
int[] dimW = {300, 45, 100, 90, 180};
int[] dimH = {35, 40};
Dimension displayDimension = new Dimension(dimW[0], dimH[0]);
Dimension regularDimension = new Dimension(dimW[1], dimH[1]);
Dimension rColumnDimension = new Dimension(dimW[2], dimH[1]);
Dimension zeroButDimension = new Dimension(dimW[3], dimH[1]);
Dimension parabolaDimension = new Dimension(dimW[4], dimH[0]);
//formatting variables
int var = 0;
double x = 0;
String stor = "";
boolean initial = true;
//variables for Parabola function
int countEquals_parab = 0;
double Angle = 0;
double Vi = 0;
double Vx = 0;
double Vy = 0;
double T_max = 0;
double Y_displ = 0;
double X_displ = 0;
double h = 0;
double k = 0;
double a_parab = 0;
boolean parabComplete = true;
boolean parabola = false;
DecimalFormat df = new DecimalFormat("#######.#####");
//variables for addressing illegal typing issues
boolean typeNum = true;
boolean typeDot = true;
JFrame frame; //for parabolaInstructions
//original calculator variables
boolean[] function = new boolean[5];
double[] temporary = {0, 0}; //store on screen values
double result = 0; //store result
public JTextArea display = new JTextArea(1, 20);
Font font = new Font("Times new Roman", Font.BOLD, 14);
CalcClass() {
super("CalcClass");
setDesign();
setSize(380, 300);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(6, 5);
setLayout(grid);
for(int i = 0; i < 5; i++) {
function[i] = false;
}
FlowLayout f1 = new FlowLayout(FlowLayout.CENTER);
FlowLayout f2 = new FlowLayout(FlowLayout.CENTER, 1, 1);
for(int i = 0; i < 6; i++) {
row[i] = new JPanel();
}
row[0].setLayout(f1);
for(int i = 1; i < 6; i++) {
row[i].setLayout(f2);
}
for(int i = 0; i < 21; i++) {
button[i] = new JButton();
button[i].setText(buttonString[i]);
button[i].setFont(font);
button[i].addActionListener(this);
}
display.setFont(font);
display.setEditable(false);
display.setPreferredSize(displayDimension);
for(int i = 0; i < 14; i++) {
button[i].setPreferredSize(regularDimension);
}
for(int i = 14; i < 18; i++) {
button[i].setPreferredSize(rColumnDimension);
}
button[18].setPreferredSize(zeroButDimension);
button[19].setPreferredSize(parabolaDimension);
button[20].setPreferredSize(rColumnDimension);
row[0].add(display);
add(row[0]);
for(int i = 0; i < 4; i++) {
row[1].add(button[i]);
}
row[1].add(button[14]);
add(row[1]);
for(int i = 4; i < 8; i++) {
row[2].add(button[i]);
}
row[2].add(button[15]);
add(row[2]);
for(int i = 8; i < 12; i++) {
row[3].add(button[i]);
}
row[3].add(button[16]);
add(row[3]);
row[4].add(button[18]);
for(int i = 12; i < 14; i++) {
row[4].add(button[i]);
}
row[4].add(button[17]);
add(row[4]);
row[5].add(button[19]);
row[5].add(button[20]);
add(row[5]);
setVisible(true);
}
public void getSqrt() {
stor = "";
initial = true;
try {
double value = Double.parseDouble(display.getText());
if(value == -100) {
format("John's Girlfriend");
} else {
value = Math.sqrt(Double.parseDouble(display.getText())); //create a value for variable, and use Maths square root to find the value
format(Double.toString(value)); //Sets display to new value
}
} catch(NumberFormatException e) {
}
typeDot = false;
typeNum = false;
}
public void getPosNeg() {
stor = "";
initial = true;
try {
double value = Double.parseDouble(display.getText()); //again creating a variable for current value
if(value != 0) { //if value is not equal to zero
value = (-1) * value; //multiplied by -1 to change the sign
format(Double.toString(value)); //Sets display to new value
} else {
}
} catch(NumberFormatException e) {
}
}
public void getResult() {
temporary[1] = Double.parseDouble(display.getText());
String temp0 = Double.toString(temporary[0]);
String temp1 = Double.toString(temporary[1]);
try {
if(temp0.contains("-")) {
String[] temp00 = temp0.split("-", 2);
temporary[0] = (Double.parseDouble(temp00[1]) * -1);
}
if(temp1.contains("-")) {
String[] temp11 = temp1.split("-", 2);
temporary[1] = (Double.parseDouble(temp11[1]) * -1);
}
} catch(ArrayIndexOutOfBoundsException e) {
}
try {
functions();
clear();
format(Double.toString(result));//display has a result
for(int i = 0; i < 5; i++) {
function[i] = false; //set all functions to false
}
} catch(NumberFormatException e) {
}
typeNum = false;
}
public void functions() {
if(function[2] == true) { //multiplication
result = temporary[0] * temporary[1];
} else if(function[3] == true) { //division
result = temporary[0] / temporary[1];
} else if(function[0] == true) { //addition
result = temporary[0] + temporary[1];
} else if(function[1] == true) { //subtraction;
result = temporary[0] - temporary[1];
} else if(function[4] == true) {
result = Math.pow(temporary[0], temporary[1]);
} else {
result = temporary[1];
}
}
double a_quadratic = 0;
double b = 0;
double c = 0;
double x1 = 0;
double x2 = 0;
double discr = 0;
int countEquals_quadratic = 0;
public void quadraticFormula() {
if(countEquals_parab == 0) {
a_quadratic = Double.parseDouble(display.getText());
clear();
display.setText("b = ");
}
if(countEquals_parab == 1) {
b = Double.parseDouble(display.getText());
display.setText("c = ");
}
if(countEquals_parab == 2) {
c = Double.parseDouble(display.getText());
discr = (Math.pow(b, 2) - 4 * a_quadratic * c); //stores the value of the discriminant
if(discr >= 0) {
x1 = (-b + Math.sqrt(b * b - 4 * a_quadratic * c)) / (2 * a_quadratic);
x2 = (-b - Math.sqrt(b * b - 4 * a_quadratic * c)) / (2 * a_quadratic);
}
}
}
public void parabolaButton() {
double G = 9.81;
if(countEquals_parab == 0) {
Vi = Double.parseDouble(display.getText());
clear();
display.setText("Angle of release: ");
}
if(countEquals_parab == 1) {
Angle = Double.parseDouble(display.getText());
if((Angle > 90.0) || (Angle < 0.0)) {
display.setText("Sorry, not a valid angle");
countEquals_parab = 3;
} else {
Angle = (Math.PI / 180.0) * Angle; //converting degrees into radians
Vx = Vi * Math.cos(Angle); //Calculating x component
Vy = Vi * Math.sin(Angle); //Calculating y component
//Finding time
T_max = Vy / G; //time to max height
//Calculating vertex coordinates
Y_displ = (Vy * Vy / (2 * G));
X_displ = Vx * T_max;
//finding a
a_parab = (-Y_displ) / (X_displ * X_displ);
display.setText("The equation of the parabola is \ny = " + df.format(a_parab) + "(x - " + df
.format(h) + ")^2 + " + df.format(k));
}
}
if(countEquals_parab == 2) {
display.setText("Time to get to max height = " + df.format(T_max));
}
if(countEquals_parab == 3) {
clearFunction();
countEquals_parab = -1;
parabola = false;
parabComplete = true;
}
countEquals_parab++;
}
public void var() {
var++;
if(var > 8) {
var = 1;
}
if(var == 1) {
format("x");
}
}
public final void setDesign() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e) {
}
}
public void format(String get) {
//get stores the incoming values temporarily
//get is transferred to a new value for permanent storage
//print the permanent storage value
//new number is added, stored temporarily in get
//get is added to permanent storage
//print permanent storage value
double spaceFix = 0;
if(initial == true) {
stor = get;
initial = false;
} else if(initial == false) {
stor = stor + get;
}
spaceFix = stor.length() / 4;
int numberOfSpaces = 56 - stor.length() + (int) spaceFix;
String format = String.format("%" + numberOfSpaces + "s", stor);
display.setText(format);
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == button[0]) {
numberButtons("7");
}
if(ae.getSource() == button[1]) {
numberButtons("8");
}
if(ae.getSource() == button[2]) {
numberButtons("9");
}
if(ae.getSource() == button[3]) {
operatorButtons(0); //add function[0]
}
if(ae.getSource() == button[4]) {
numberButtons("4");
}
if(ae.getSource() == button[5]) {
numberButtons("5");
}
if(ae.getSource() == button[6]) {
numberButtons("6");
}
if(ae.getSource() == button[7]) {
operatorButtons(1); //subtract function[1]
}
if(ae.getSource() == button[8]) {
numberButtons("1");
}
if(ae.getSource() == button[9]) {
numberButtons("2");
}
if(ae.getSource() == button[10]) {
numberButtons("3");
}
if(ae.getSource() == button[11]) {
operatorButtons(2); //multiplication function[2]
}
if(ae.getSource() == button[12]) {
if(typeDot == false) {
} else {
numberButtons(".");
typeDot = false;
}
}
if(ae.getSource() == button[13]) {
operatorButtons(3); //divide function[3]
}
if(ae.getSource() == button[14]) {
clearFunction();
parabola = false;
parabComplete = true;
}
if(ae.getSource() == button[15]) {
getSqrt();
}
if(ae.getSource() == button[16]) {
getPosNeg();
}
if((ae.getSource() == button[17]) && display.getText().equals("")) {
} else if((ae.getSource() == button[17]) && (parabola == false)) {
getResult();
} else if((ae.getSource() == button[17]) && (parabola == true)) {
parabolaButton();
}
if(ae.getSource() == button[18]) {
numberButtons("0");
}
if(ae.getSource() == button[19]) {
clearFunction();
parabolaInstructions();
parabola = true;
parabComplete = false;
display.setText("Initial velocity: ");
}
if(ae.getSource() == button[20]) {
operatorButtons(4);//powerFunction();
}
}
public void parabolaInstructions() {
//Create the dialog.
final JDialog dialog = new JDialog(frame, "How to use the Parabola function");
//Add contents to it. It must have a close button,
//since some L&Fs (notably Java/Metal) don't provide one
//in the window decorations for dialogs.
JLabel label = new JLabel("<html><p align=center>" + "Step 1: Type in the initial velocity and press the \"=\" button<br>" + "Step 2: Type in the angle of Release (make sure that it is between 0 and 90)<br>" + "Step 3: Press the \"=\" button to scroll through the results<br>" + "Step 4: Profit");
label.setHorizontalAlignment(JLabel.CENTER);
Font font = label.getFont();
label.setFont(label.getFont().deriveFont(font.PLAIN, 14.0f));
JButton closeButton = new JButton("Ok");
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
dialog.dispose();
}
});
JPanel closePanel = new JPanel();
closePanel.setLayout(new BoxLayout(closePanel, BoxLayout.LINE_AXIS));
closePanel.add(Box.createHorizontalGlue());
closePanel.add(closeButton);
closePanel.setBorder(BorderFactory.
createEmptyBorder(0, 0, 5, 5));
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(label, BorderLayout.CENTER);
contentPane.add(closePanel, BorderLayout.PAGE_END);
contentPane.setOpaque(true);
dialog.setContentPane(contentPane);
//Show it.
dialog.setSize(new Dimension(400, 200));
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
public void numberButtons(String i) {
if(typeNum == false) {
display.setText("");
format(i);
} else {
format(i);
}
typeNum = true;
}
public void operatorButtons(int funct) {
if(display.getText().equals("")) {
} else {
temporary[0] = Double.parseDouble(display.getText());
function[funct] = true;
clear();
}
}
public void clearFunction() {
clear();
try {
for(int i = 0; i < 5; i++) {
function[i] = false;
}
for(int i = 0; i < 2; i++) {
temporary[i] = 0;
}
} catch(NullPointerException e) {
}
//For parabola()
Vi = 0;
Vx = 0;
Vy = 0;
T_max = 0;
Y_displ = 0;
X_displ = 0;
h = 0;
k = 0;
a_parab = 0;
}
public void clear() {
display.setText("");
stor = "";
typeDot = true;
initial = true;
}
public static void main(String[] arguments) {
CalcClass c = new CalcClass();
}
}
Ok so now you've seen my mess... I sort-of know what I should do and YES I did some research but I feel it would be much easier to learn organization through example or a nice push than it would be from reading articles that tell you ultra-hypothetical or loosely-analogous examples of what objects are. Note: I tried using methods to organize and my class looks much better than what it did (I also made the whole thing an object to be called upon at the bottom which is pretty much useless).
If you use eclipse, try:
Window > Prefferences > Java > Editor > Save Actions
Check "perform the selected actions on save", "Additional Actions" and click "Configure".
Using eclipse's Save Actions can be really useful in real life coding, but you will probably learn some neat java tricks going through the Save Actions wizard.
Java is an Object Oriented language. You need to take advantage of that fact.
Use classes to separate your code into different logical / structural components. Learn how to use OOP. Follow SOLID design and use design patterns.
Another important thing is to know your language. Start by reading basic classes javadocs and relevant sections of the java spec. I would begin with deeply understanding the different types of java (class, interface, enum and inner / nested / anonymous types) and the different modifiers (private, public, protected, static, abstract, final, default).
Some other eclipse's short cuts:
CTRL-A, CTRL-I ("indentation") will fix your code indentation.
CTRL-SHIFT-O ("organize imports") will omit redundant imports.
You might consider taking a look at Code Complete, which deals with the issues that you're concerned with here, and otherwise is just a classic in our field that every serious developer should read.
In general, when you're organizing code you should do so with a few things in mind: readability and atomicity. These two factors apply to code on every level of an application, from variable naming, routines, methods, classes, packages, and so on.
Readability is a simple idea: can a human being read this code and understand it? To gauge the readability of the code all you have to do is read it! Do variable names help the reader understand what something is? Are routines and classes properly formatted and not needlessly complex? Have you removed all code that isn't being used? Is your code written in a logical progression?
Atomicity is the idea that everything should have one purpose. A function or method should (usually) do one thing and one thing only. A class should usually be a logical grouping of related methods and fields serving some type of unique purpose, and NOT a mish-mash of unrelated stuff. A package should also contain a set of related files. Same with a project, and so on.
The main benefit of atomicity is that once you get into more involved applications it's actually much easier to debug and isolate issues in your code because you know where stuff is. For instance: I have a database access error! Good thing I have a package that's specifically defined for my database access objects.
I know when I was just getting started in the field this was something that threw me off too. It might not be until you do a lot of coding within more significant apps that you really start to understand best practices and why people build stuff a certain way.
Thanks to everyone who contributed to my problem, I completely scrapped this garbage and made it 1000 times better. I knew from the beginning it was poorly made and I wanted to fix it, I just didn't know where to start. After reading all the advice that was given, watching a few tutorials and brushing up on some simple java concepts (modifiers, jswing, etc), I ended up making a new one that is in MVC format (Yay, order and efficiency). Now all my new variables are actually meaningful (Thanks #maaartinus for helping me realize that many of my variables were poorly named and made my whole program unnecessarily complicated). Also, I tried to work on SRP (Not 100% sure if I completely did it but with the program organized it will be easy to change things) and I plan on adding units later for good practice (Thank you, #Robert Snyder). This new GUI is ugly but that can always be changed later and since It is now in MVC format the job will be easier.
Here is what I did (not finished and far from perfect but a step in the right direction):
CalcGui.java
package com.Calculator;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CalcGui extends JFrame {
private static final long serialVersionUID = 1L;
private String[] operatorsList = { "+", "-", "*", "/", "^" };
// Row 1
private JTextField firstNumber = new JTextField(10);
private JComboBox<String> operator = new JComboBox<>(operatorsList);
private JTextField secondNumber = new JTextField(10);
private JButton calculateButton = new JButton("Calculate");
private JTextField calcSolution = new JTextField(20);
// Row 2
private JLabel sqrtSymbol = new JLabel("√");
private JTextField sqrtNumber = new JTextField(10);
private JButton sqrtCalcButton = new JButton("Calculate");
private JTextField sqrtCalcSolution = new JTextField(20);
// Row 3
private JLabel quadraticLabel1 = new JLabel("A = ");
private JTextField quadraticFirstNumber = new JTextField(5);
private JLabel quadraticLabel2 = new JLabel("B = ");
private JTextField quadraticSecondNumber = new JTextField(5);
private JLabel quadraticLabel3 = new JLabel("C = ");
private JTextField quadraticThirdNumber = new JTextField(5);
private JButton quadraticCalcButton = new JButton("Calculate");
private JLabel quadraticTextBefore = new JLabel("x =");
private JTextField firstQuadraticCalcSolution = new JTextField(3);
private JLabel quadraticTextMiddle = new JLabel("and x =");
private JTextField secondQuadraticCalcSolution = new JTextField(3);
CalcGui() {
JPanel calcPanel = new JPanel(new BorderLayout());
FlowLayout Default = new FlowLayout(FlowLayout.LEFT);
JPanel row1 = new JPanel(Default);
JPanel row2 = new JPanel(Default);
JPanel row3 = new JPanel(Default);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(650, 150);
row1.add(firstNumber);
row1.add(operator);
row1.add(secondNumber);
row1.add(calculateButton);
row1.add(calcSolution);
row2.add(sqrtSymbol);
row2.add(sqrtNumber);
row2.add(sqrtCalcButton);
row2.add(sqrtCalcSolution);
row3.add(quadraticLabel1);
row3.add(quadraticFirstNumber);
row3.add(quadraticLabel2);
row3.add(quadraticSecondNumber);
row3.add(quadraticLabel3);
row3.add(quadraticThirdNumber);
row3.add(quadraticCalcButton);
row3.add(quadraticTextBefore);
row3.add(firstQuadraticCalcSolution);
row3.add(quadraticTextMiddle);
row3.add(secondQuadraticCalcSolution);
calcPanel.add(row1, BorderLayout.NORTH);
calcPanel.add(row2, BorderLayout.CENTER);
calcPanel.add(row3, BorderLayout.SOUTH);
this.add(calcPanel);
}
// basic calculations methods
public double getFirstNumber() {
return Double.parseDouble(firstNumber.getText());
}
public String getOperator() {
return (String) operator.getSelectedItem();
}
public double getSecondNumber() {
return Double.parseDouble(secondNumber.getText());
}
public void setCalcSolution(double solution) {
calcSolution.setText(Double.toString(solution));
}
void addCalculateListener(ActionListener listenForCalcButton) {
calculateButton.addActionListener(listenForCalcButton);
}
void displayErrorMessage(String errorMessage) {
JOptionPane.showMessageDialog(this, errorMessage);
}
// Square root function methods
public double getSqrtNumber() {
return Double.parseDouble(sqrtNumber.getText());
}
public void setSqrtCalcSolution(double solution) {
sqrtCalcSolution.setText(Double.toString(solution));
}
void addSqrtCalcListener(ActionListener listenForSqrtCalcButton) {
sqrtCalcButton.addActionListener(listenForSqrtCalcButton);
}
// Quadratic formula Methods
public double getQuadraticFirstNumber() {
return Double.parseDouble(quadraticFirstNumber.getText());
}
public double getQuadraticSecondNumber() {
return Double.parseDouble(quadraticSecondNumber.getText());
}
public double getQuadraticThirdNumber() {
return Double.parseDouble(quadraticThirdNumber.getText());
}
public void setFirstQuadraticCalcSolution(double solution) {
firstQuadraticCalcSolution.setText(Double.toString(solution));
}
public void setSecondQuadraticCalcSolution(double solution) {
secondQuadraticCalcSolution.setText(Double.toString(solution));
}
void addQuadraticCalcListener(ActionListener listenForQuadraticCalcButton) {
quadraticCalcButton.addActionListener(listenForQuadraticCalcButton);
}
}
CalcModel.java
package com.Calculator;
public class CalcModel {
private double calcValue;
public void calculate(double firstNumber, double secondNumber,
String operator) {
if (operator.equals("+")) {
calcValue = firstNumber + secondNumber;
}
if (operator.equals("-")) {
calcValue = firstNumber - secondNumber;
}
if (operator.equals("*")) {
calcValue = firstNumber * secondNumber;
}
if (operator.equals("/")) {
calcValue = firstNumber / secondNumber;
}
if (operator.equals("^")) {
calcValue = Math.pow(firstNumber, secondNumber);
}
}
public double getCalcValue() {
return calcValue;
}
}
SqrtCalcModel.java
package com.Calculator;
public class SqrtCalcModel {
private double sqrtCalcValue;
public void sqrt(double number) {
sqrtCalcValue = Math.sqrt(number);
}
public double getSqrtCalcValue() {
return sqrtCalcValue;
}
}
QuadraticCalcModel.java
package com.Calculator;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class QuadraticCalcModel {
private double firstQuadraticCalcValue;
private double secondQuadraticCalcValue;
public void quadraticFormula(double a, double b, double c) {
double discriminant = (b * b) - (4 * a * c);
if (discriminant >= 0) {
firstQuadraticCalcValue = (Math.sqrt((b * b) - (4 * a * c)) + (-b))
/ (2 * a);
secondQuadraticCalcValue = (Math.sqrt((b * b) - (4 * a * c)) - (-b))
/ (2 * a);
}
else {
JFrame parent = new JFrame();
JOptionPane.showMessageDialog(parent,
"This function has no real roots.");
}
}
public double getFirstQuadraticValue() {
return firstQuadraticCalcValue;
}
public double getSecondQuadraticValue() {
return secondQuadraticCalcValue;
}
}
CalculatorControler.java
package com.Calculator;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CalculatorController {
private CalcGui theGui;
private CalcModel theCalcModel;
private SqrtCalcModel theSqrtCalcModel;
private QuadraticCalcModel theQuadraticCalcModel;
public CalculatorController(CalcGui theGui, CalcModel theCalcModel,
SqrtCalcModel theSqrtCalcModel,
QuadraticCalcModel theQuadraticCalcModel) {
this.theGui = theGui;
this.theCalcModel = theCalcModel;
this.theSqrtCalcModel = theSqrtCalcModel;
this.theQuadraticCalcModel = theQuadraticCalcModel;
this.theGui.addCalculateListener(new CalcListener());
this.theGui.addSqrtCalcListener(new SqrtCalcListener());
this.theGui.addQuadraticCalcListener(new QuadraticCalcListener());
}
class CalcListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
double firstNumber, secondNumber = 0;
String operator;
try {
firstNumber = theGui.getFirstNumber();
operator = theGui.getOperator();
secondNumber = theGui.getSecondNumber();
theCalcModel.calculate(firstNumber, secondNumber, operator);
theGui.setCalcSolution(theCalcModel.getCalcValue());
}
catch (NumberFormatException ex) {
System.out.println(ex);
theGui.displayErrorMessage("You Need to Enter 2 Numbers");
}
}
}
class SqrtCalcListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
double number = 0;
try {
number = theGui.getSqrtNumber();
theSqrtCalcModel.sqrt(number);
theGui.setSqrtCalcSolution(theSqrtCalcModel.getSqrtCalcValue());
}
catch (NumberFormatException ex) {
System.out.println(ex);
theGui.displayErrorMessage("You Need to enter a Number");
}
}
}
class QuadraticCalcListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
double a, b, c = 0;
try {
a = theGui.getQuadraticFirstNumber();
b = theGui.getQuadraticSecondNumber();
c = theGui.getQuadraticThirdNumber();
theQuadraticCalcModel.quadraticFormula(a, b, c);
theGui.setFirstQuadraticCalcSolution(theQuadraticCalcModel
.getFirstQuadraticValue());
theGui.setSecondQuadraticCalcSolution(theQuadraticCalcModel
.getSecondQuadraticValue());
}
catch (NumberFormatException ex) {
System.out.println(ex);
theGui.displayErrorMessage("You need to enter 3 numbers.");
}
}
}
}
MVCCalculator.java
package com.Calculator;
public class MVCCalculator {
public static void main(String[] args) {
CalcGui theGui = new CalcGui();
CalcModel theCalcModel = new CalcModel();
SqrtCalcModel theSqrtCalcModel = new SqrtCalcModel();
QuadraticCalcModel theQuadraticCalcModel = new QuadraticCalcModel();
new CalculatorController(theGui, theCalcModel, theSqrtCalcModel,
theQuadraticCalcModel);
theGui.setVisible(true);
}
}

Trying to make a functional calculator in java, I can't figure out where I'm going wrong [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'd like to start off saying that I'm still really new to java, but I promise this is not a troll post. So I have to make a functional four function calculator for school. It's really basic but for some reason I can't get it to work properly. I was given the following as example code, my teacher told us to infer the rest.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator implements ActionListener
{
JFrame f1;
JTextField display;
JButton b1,b2,addb,equalsb,clearb;
JPanel p1;
String value,operation;
double secondnum, total;
public Calculator()
{
value = "";
total = 0.0;
secondnum = 0.0;
f1 = new JFrame("Calculator");
f1.setSize(400,100);
Container c1 = f1.getContentPane();
display = new JTextField(15);
b1 = new JButton("1");
b1.addActionListener(this); // adds a Listener for Button b1
b2 = new JButton("2");
b2.addActionListener(this);
addb = new JButton("+");
addb.addActionListener(this);
equalsb = new JButton("=");
equalsb.addActionListener(this);
clearb = new JButton("C");
clearb.addActionListener(this);
p1 = new JPanel();
p1.add(display);
p1.add(b1);
p1.add(b2);
p1.add(addb);
p1.add(equalsb);
p1.add(clearb);
c1.add(p1);
f1.show();
}
public void actionPerformed(ActionEvent event)
{
if (event.getSource()== b1)
value = value + "1";
if (event.getSource() == b2)
value = value + "2";
if (event.getSource() == clearb)
{
total = 0.0;
secondnum = 0.0;
value = "";
}
if (event.getSource() == addb)
{
total = Double.parseDouble(value);
operation = "add";
value = "";
}
if (event.getSource() == equalsb)
{
secondnum = Double.parseDouble(value);
if(operation.equals("add"))
total = total + secondnum;
value = ""+ total; //value becomes what the total is to be diplays
}
display.setText(value);
}
}
This works, so from it I created the following. I'm pretty sure i'm going wrong in the function keys, but I have no clue where I messed up.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Calculator implements ActionListener
{
JFrame f;
Container c;
JPanel p;
JTextField display;
JButton b1, b2, b3, bdiv, b5, b6, b7, bmult, b9, b10, b11, badd, b13, bdecimal, bequals, bsub, bclear;
String value, operation;
double secondnum, total;
public Calculator()
{
value = "";
total = 0.0;
secondnum = 0.0;
f = new JFrame("Calculator");
f.setSize(333,225);
c = f.getContentPane();
p = new JPanel();
display = new JTextField(20);
b1 = new JButton("7");
b1.addActionListener(this);
b2 = new JButton("8");
b2.addActionListener(this);
b3 = new JButton("9");
b3.addActionListener(this);
bdiv = new JButton("/");
bdiv.addActionListener(this);
b5 = new JButton("4");
b5.addActionListener(this);
b6 = new JButton("5");
b6.addActionListener(this);
b7 = new JButton("6");
b7.addActionListener(this);
bmult = new JButton("x");
bmult.addActionListener(this);
b9 = new JButton("1");
b9.addActionListener(this);
b10 = new JButton("2");
b10.addActionListener(this);
b11 = new JButton("3");
b11.addActionListener(this);
badd = new JButton("+");
badd.addActionListener(this);
b13 = new JButton("0");
b13.addActionListener(this);
bdecimal = new JButton(".");
bdecimal.addActionListener(this);
bequals = new JButton("=");
bequals.addActionListener(this);
bsub = new JButton("-");
bsub.addActionListener(this);
bclear = new JButton("C");
bclear.addActionListener(this);
p.setBackground(Color.green);
p.add(display);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bdiv);
p.add(b5);
p.add(b6);
p.add(b7);
p.add(bmult);
p.add(b9);
p.add(b10);
p.add(b11);
p.add(badd);
p.add(b13);
p.add(bdecimal);
p.add(bequals);
p.add(bsub);
p.add(bclear);
c.add(p);
f.show();
}
public void actionPerformed (ActionEvent event)
{
if(event.getSource() == b1)
{
value = value + "7";
}
if(event.getSource() == b2)
{
value = value + "8";
}
if(event.getSource() == b3)
{
value = value + "9";
}
if(event.getSource() == b5)
{
value = value + "4";
}
if(event.getSource() == b6)
{
value = value + "5";
}
if(event.getSource() == b7)
{
value = value + "6";
}
if(event.getSource() == b9)
{
value = value + "1";
}
if(event.getSource() == b10)
{
value = value + "2";
}
if(event.getSource() == b11)
{
value = value + "3";
}
if(event.getSource() == b13)
{
value = value + "0";
}
if(event.getSource() == bdecimal)
{
value = value + ".";
}
if(event.getSource() == badd)
{
total = Double.parseDouble(value);
operation = "add";
value = "";
}
if(event.getSource() == bmult)
{
total = Double.parseDouble(value);
operation = "multiply";
value = "";
}
if(event.getSource() == bsub)
{
total = Double.parseDouble(value);
operation = "subtract";
value = "";
}
if(event.getSource() == bdiv)
{
total = Double.parseDouble(value);
operation = "divide";
value = "";
}
if(event.getSource() == bclear)
{
total = 0.0;
secondnum = 0.0;
value = "";
}
if(event.getSource() == bequals)
{
secondnum = Double.parseDouble(value);
{
if(operation.equals("add));
total = total + secondnum;
}
{
if(operation.equals("subtract"));
total = total - secondnum;
}
if(operation.equals("divide"));
total = total / secondnum;
{
if(operation.equals("multiply"));
total = total * secondnum;
}
value = "" + tottal
}
display.setText(value);
}
}
Any help is much appreciated, I realize it's probably just a stupid mistake.
You have strange conditions on the end of the source code:
if(operation.equals("multiply"));
total = total * secondnum;
this won't multiply because of semicolon on the end of if
this is better:
if(operation.equals("multiply"))
total = total * secondnum;
And I cant understand your block of codes here, if you want to make if do this:
if(condition){
command1;
command2;
}
and not:
{
if(condition)
command1;
command2;
}

Button counter not upating

Trying to write a simple program to display a telephone number typed in with the buttons. I have a counter set up for each time a button is pushed to automatically insert the "-" after the 3rd and 6th number input. My counter doesn't seem to be updating on the button pushes. I can't see why. It's probably quite simple but I would greatly appreciate any help.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BorderPanel extends JPanel
{
//variables
int counter = 0;
int total;
Object source = new Object();
String display = "";
String s;
//buttons
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b0 = new JButton("0");
JButton bstar = new JButton("*");
JButton blb = new JButton("#");
JButton resetB = new JButton("RESET");
//layout managers
BorderLayout layoutB = new BorderLayout();
GridLayout layoutG = new GridLayout(4,3);
//panels
JPanel bigP = new JPanel(layoutB);
JPanel numberP = new JPanel(layoutG);
//JLabel
JLabel displayL = new JLabel();
JLabel counterL = new JLabel();
//listener
ButtonListener buttonListener = new ButtonListener();
public BorderPanel()
{
/****************START**********************/
displayL.setText(display);
numberP.add(b1);
b1.addActionListener(buttonListener);
numberP.add(b2);
b2.addActionListener(buttonListener);
numberP.add(b3);
b3.addActionListener(buttonListener);
numberP.add(b4);
b4.addActionListener(buttonListener);
numberP.add(b5);
b5.addActionListener(buttonListener);
numberP.add(b6);
b6.addActionListener(buttonListener);
numberP.add(b7);
b7.addActionListener(buttonListener);
numberP.add(b8);
b8.addActionListener(buttonListener);
numberP.add(b9);
b9.addActionListener(buttonListener);
numberP.add(bstar);
bstar.addActionListener(buttonListener);
numberP.add(b0);
b0.addActionListener(buttonListener);
numberP.add(blb);
blb.addActionListener(buttonListener);
resetB.addActionListener(buttonListener);
bigP.add(displayL, layoutB.SOUTH);
bigP.add(resetB, layoutB.EAST);
bigP.add(numberP, layoutB.CENTER);
add(counterL);
add(bigP);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
counter ++;
if (total == 3)
display += "-";
if (total == 6)
display += "-";
source = event.getSource();
if (source == b1)
display += "1";
if (source == b2)
display += "2";
if (source == b3)
display += "3";
if (source == b4)
display += "4";
if (source == b5)
display += "5";
if (source == b6)
display += "6";
if (source == b7)
display += "7";
if (source == b8)
display += "8";
if (source == b9)
display += "9";
if (source == b0)
display += "0";
if (source == bstar)
display += "*";
if (source == blb)
display += "#";
if (source == resetB)
display = "";
counter = 0;
displayL.setText(display);
counterL.setText("" + counter);
}
}
}
You need to include braces for this if statement otherwise the counter = 0 is always executed. If you don't use braces for a control structure, it only includes the very next statement in the scope of the structure.
So your code
if (source == resetB)
display = "";
counter = 0;
is actually equivalent to
if (source == resetB)
{
display = "";
}
counter = 0;
You need to enclose both statements in braces. This is why you should get in the habit of using braces for control structures (if/else/for/while etc) unless you're sure it won't cause any confusion whatsoever. Even then, you risk something like this happening.
if (source == resetB)
{
display = "";
counter = 0;
}
Also, you are setting total but never using it, so although it will add to counter it won't display the hyphens.
You need to change both usages of total to counter and move it after the number is added to the display, otherwise you will get 00-000-00000 instead of 000-000-0000
So it will look like:
if (source == b1)
display += "1";
//...etc
if (source == blb)
display += "#";
if (source == resetB)
{
display = "";
counter = 0;
}
if (counter == 3)
display += "-";
if (counter == 6)
display += "-";

Why is my ItemListener program not allowing me to select an option from two different JComboBoxes in Java?

My program will only do one JcomboBox at a time when I am trying to get both numbers to be added together to display the final number.
It allows me to run the program, but it will not display the final price because it does not want to select two things at once.
Here is the code for my program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CottageRental2 extends JFrame implements ItemListener{
// Declare all instance data (primitives and objects used)
private int WIDTH = 676;
private int HEIGHT = 321;
Container con;
private JLabel label1;
private JLabel label2;
private JLabel label3;
JComboBox cbox1;
JComboBox cbox2;
String [ ] roomChoice = {"1 Bedroom: $600","2 Bedroom: $800","3 Bedroom: $1000"};
String [ ] activityChoice = {"Horse Back Riding: $60","Rafting: $40","Row Boat Rental: $50"};
ImageIcon icon1 = new ImageIcon("C:\\Users\\Coding\\Desktop\\cottage.jpeg");
Font f1 = new Font("Ariel", Font.BOLD, 30);
//constructor
public CottageRental2(){
super("Cottage Rental");
con = getContentPane();
con.setLayout(new BorderLayout());
con.setBackground(Color.GRAY);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void createGUI(){
label1 = new JLabel("Woodberry Cottage Rental", JLabel.CENTER);
label1.setFont(f1);
label1.setForeground(Color.WHITE);
label2 = new JLabel("Rental Amount Due: $660", JLabel.CENTER);
label2.setFont(f1);
label2.setForeground(Color.WHITE);
label3 = new JLabel(icon1);
cbox1 = new JComboBox();
cbox1.addItem(roomChoice[0]);
cbox1.addItem(roomChoice[1]);
cbox1.addItem(roomChoice[2]);
cbox1.addItemListener(this);
cbox2 = new JComboBox();
cbox2.addItem(activityChoice[0]);
cbox2.addItem(activityChoice[1]);
cbox2.addItem(activityChoice[2]);
cbox2.addItemListener(this);
con.add(label1, BorderLayout.NORTH);
con.add(label2, BorderLayout.SOUTH);
con.add(label3, BorderLayout.CENTER);
con.add(cbox1, BorderLayout.WEST);
con.add(cbox2, BorderLayout.EAST);
}
public void itemStateChanged(ItemEvent event){
Object source = event.getSource();
int price1 = 0;
int price2 = 0;
if(source == cbox1){
int roomIndex = cbox1.getSelectedIndex();
if(roomIndex == 0){
price1 = 600;
}
if(roomIndex == 1){
price1 = 800;
}
if(roomIndex == 2){
price1 = 1000;
}
}
if(source == cbox2){
int activityIndex = cbox2.getSelectedIndex();
if(activityIndex == 0){
price2 = 60;
}
if(activityIndex == 1){
price2 = 40;
}
if(activityIndex == 2){
price2 = 50;
}
}
label2.setText("Rental Amount Due: $" + (price1 + price2));
}
public static void main(String[] args){
CottageRental2 object = new CottageRental2();
object.createGUI();
object.setSize(675, 320);
}
}
Your problem is your if (source == ...) if blocks which prevent the program from getting the selected item from the other JComboBox, the one that isn't being actively selected.
One solution: get rid of the offending if blocks that test for the source of the event in the listener:
public void itemStateChanged(ItemEvent event) {
// Object source = event.getSource();
int price1 = 0;
int price2 = 0;
// if(source == cbox1){
int roomIndex = cbox1.getSelectedIndex();
if (roomIndex == 0) {
price1 = 600;
} else if (roomIndex == 1) {
price1 = 800;
} else if (roomIndex == 2) {
price1 = 1000;
}
// }
// if(source == cbox2){
int activityIndex = cbox2.getSelectedIndex();
if (activityIndex == 0) {
price2 = 60;
} else if (activityIndex == 1) {
price2 = 40;
} else if (activityIndex == 2) {
price2 = 50;
}
// }
label2.setText("Rental Amount Due: $" + (price1 + price2));
}
Also, it would be safer if you use some else if blocks in your item selection statements.

Java button question

I am trying to get the user to input 2 fields. One is the volume of the pool and one is the volume of the hut tub. This then calculates the price of each, what I am having trouble is with if the user enters volume for the pool, then they can't enter anything for the hot tub and vise versa. This is what I have so far. Do I need to have 2 separate fields for this, or how can it be done?
Pretty much the string errors = ""; can be removed once I figure out how to only allow them to enter one set of numbers. Here is the calculate portion, the other part of the code is just the 3 labels.
pricePanel = new JPanel(new FlowLayout());
final JRadioButton poolPrice= new JRadioButton("Pool");
final JRadioButton tubPrice = new JRadioButton("Hot Tub");
poolPrice.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(poolPrice);
group.add(tubPrice);
pricePanel.add(poolPrice);
pricePanel.add(tubPrice);
pricePanel.add(new JLabel("Enter the pool's volume: "));
final JTextField poolField = new JTextField(10);
pricePanel.add(poolField);
pricePanel.add(new JLabel("Enter the tub's volume: "));
final JTextField tubField = new JTextField(10);
pricePanel.add(tubField);
JButton calculatePrice = new JButton("Calculate Price");
calculatePrice.setMnemonic('C');
pricePanel.add(calculatePrice);
pricePanel.add(createExitButton());
pricePanel.add(new JLabel("The price is:$ "));
final JTextField priceField = new JTextField(10);
priceField.setEditable(false);
pricePanel.add(priceField);
calculatePrice.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double pool = Double.parseDouble (poolField.getText());
double tub = Double.parseDouble(tubField.getText());
double price;
if (poolPrice.isSelected()) {
price = pool * 100;
} else {
price = tub * 75;
}
priceField.setText(df.format(price));
}
});
};
ActionListener priceListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == poolPrice) {
tubLabel.setEnabled(false);
tubField.setEnabled(false);
messageArea.setVisible(true);
} else if (e.getSource() == tubPrice) {
poolLabel.setEnabled(false);
poolField.setEnabled(false);
messageArea.setVisible(true);
}
}
};
poolPrice.addActionListener(priceListener);
tubPrice.addActionListener(priceListener);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
hotTubsPanel = new JPanel(new FlowLayout());
final JRadioButton roundTub = new JRadioButton("Round Tub");
final JRadioButton ovalTub = new JRadioButton("Oval Tub");
roundTub.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(roundTub);
group.add(ovalTub);
hotTubsPanel.add(roundTub);
hotTubsPanel.add(ovalTub);
hotTubsPanel.add(new JLabel("Enter the tub's length: "));
final JTextField lengthField = new JTextField(10);
hotTubsPanel.add(lengthField);
final JLabel widthLabel = new JLabel("Enter the tub's width*: ");
widthLabel.setEnabled(false);
hotTubsPanel.add(widthLabel);
final JTextField widthField = new JTextField(10);
widthField.setEnabled(false);
hotTubsPanel.add(widthField);
hotTubsPanel.add(new JLabel("Enter the tub's depth: "));
final JTextField depthField = new JTextField(10);
hotTubsPanel.add(depthField);
JButton calculateVolume = new JButton("Calculate Volume");
calculateVolume.setMnemonic('C');
hotTubsPanel.add(calculateVolume);
hotTubsPanel.add(createExitButton());
hotTubsPanel.add(new JLabel("The tub's volume is: "));
final JTextField volumeField = new JTextField(10);
volumeField.setEditable(false);
hotTubsPanel.add(volumeField);
final JTextArea messageArea = createMessageArea(1, 25,
"*Width will be set to the same value as length");
hotTubsPanel.add(messageArea);
calculateVolume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (roundTub.isSelected()) {
widthField.setText(lengthField.getText());
}
ValidationResult result = validateFields(new JTextField[] {
lengthField, widthField, depthField });
String errors = "";
if (result.filled != 3) {
errors += "Please fill out all fields! ";
}
if (result.valid != 3 && result.filled != result.valid) {
errors += "Please enter valid numbers!";
}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
} else {
messageArea.setVisible(false);
double length = Double.parseDouble(lengthField.getText());
double width = Double.parseDouble(widthField.getText());
double depth = Double.parseDouble(depthField.getText());
double volume;
if (roundTub.isSelected()) {
volume = Math.PI * Math.pow(length / 2.0, 2) * depth;
} else {
volume = Math.PI * Math.pow(length * width, 2) * depth;
}
volumeField.setText(df.format(volume));
}
}
});
ActionListener tubsListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == roundTub) {
widthLabel.setEnabled(false);
widthField.setEnabled(false);
widthField.setText(lengthField.getText());
messageArea.setText("Tub's width set to length");
messageArea.setVisible(true);
} else if (e.getSource() == ovalTub) {
widthLabel.setEnabled(true);
widthField.setEnabled(true);
messageArea.setVisible(false);
}
}
};
roundTub.addActionListener(tubsListener);
ovalTub.addActionListener(tubsListener);
}
Two text fields and only one result field could be confusing for the user. If there's only going to be one result field, there should only be one text field as well. The radio buttons Stian suggested would work, or even having two buttons, one for pool and one for hot tub (this would require only one click to get the other price). You should also have something in the result field indicating which one has been calculated, like "Pool price: $XX.XX" or "Hot tub price: $XX.XX". If you went with the buttons idea and labeled the buttons "Pool" and "Hot Tub", you could even do something fancy with the result, like setText(e.getActionCommand()+" price:"+price);.
Also, if (errors != "") is always going to be true. You are testing if your errors object is the same object as a new String object you are creating; it never will be. You should instead test for if (!errors.equals("")) or if (errors.length()!=0).

Categories

Resources