PDA

View Full Version : Java death



jdubb5005
05-04-2006, 11:40 PM
Ok so a few of you had some help for me before on java, this time I think it is a little more involved. I need to have the program do the operation of the button I push. So type in 5 hit add then type in 2 then hit multiply and I have 10. It seems like my action event is not working.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code ="Calculator" width=300 height=200>
</applet>
*/

public class Calculator extends JApplet
implements ActionListener
{
private JTextField operandText;
private JTextField answerText;
private JButton addButton;
private JButton subtractButton;
private JButton multiplyButton;
private JButton divideButton;
private JButton clearButton;

private double total = 0;

public void init()
{
setLayout (new GridLayout(7, 2, 5, 5));

operandText = buildAField ("Operand", true);
addButton = buildAButton("Add", new Color(155,155,255));
subtractButton = buildAButton("Subtract", new Color(155,155,255));
multiplyButton = buildAButton("Multiply", new Color(155,155,255));
divideButton = buildAButton("Divide", new Color(155,155,255));
clearButton = buildAButton("Clear", new Color(155,155,255));
answerText = buildAField("Answer", false);

}//init

private JButton buildAButton (String buttonName,
Color myColor)
{
JButton myButton = new JButton(buttonName);
add (new JLabel(""));
add (myButton);
myButton.setBackground (myColor);
myButton.addActionListener (this);
myButton.setEnabled(true);
return myButton;
}

private JTextField buildAField (String labelName,
boolean editable)
{
JTextField myTextField = new JTextField();
JLabel myLabel = new JLabel (labelName);
myLabel.setHorizontalAlignment(SwingConstants.RIGH T);
add(myLabel);
add(myTextField);
myTextField.setHorizontalAlignment(SwingConstants. RIGHT);
myTextField.setEditable(editable);
if (!editable)
myTextField.setFocusable(false);
return myTextField;
}

public void actionPerformed (ActionEvent ae)
{
double operator;

operator = Double.parseDouble(operandText.getText());

if(ae.getSource () == addButton)
total = total + operator;
else if(ae.getSource () == subtractButton)
total = total - operator;
else if(ae.getSource () == multiplyButton)
if (operator == 0)
total = 0;
else
total = total * operator;
else if(ae.getSource () == divideButton)
{
if (operator == 0)
total = 0;
else
total = total / operator;
}
else if(ae.getSource () == clearButton)
{
clearMethod ();
}
answerText.setText (String.format ("%10.5", total));
operandText.setText("");
operandText.requestFocusInWindow();
}

public void clearMethod()
{

operandText.setText("");
operandText.requestFocusInWindow();
total = 0;
answerText.setText (String.format ("%10.5", total));
}

}//class