Rewriting Calculator2.java as an application using layout manager
Flow, Border, or Grid.
Make Calculator2.java an application using one of the layout.
-------------------------------------------------------------------------------import
java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.applet.Applet;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.Box;
public class Calculator2 extends Applet
{
private JTextField operand1;
private JTextField operand2;
private JTextField result;
private JLabel plusLabel;
private JLabel equalsLabel;
private JButton addButton;
private JButton subtractButton;
private JButton multiplyButton;
private JButton divideButton;
public void init()
{
operand1 = new JTextField(10);
plusLabel = new JLabel(" ? ");
operand2 = new JTextField(10);
equalsLabel = new JLabel("=");
result = new JTextField(10);
result.setEditable(false);
addButton = new JButton("+");
subtractButton = new JButton("-");
multiplyButton = new JButton("x");
divideButton = new JButton("/");
Box vBox = Box.createVerticalBox();
Box dataBox = Box.createHorizontalBox();
dataBox.add(operand1);
dataBox.add(plusLabel);
dataBox.add(operand2);
dataBox.add(equalsLabel);
dataBox.add(result);
vBox.add(dataBox);
Box buttonBox = Box.createHorizontalBox();
buttonBox.add(addButton);
buttonBox.add(subtractButton);
buttonBox.add(multiplyButton);
buttonBox.add(divideButton);
vBox.add(buttonBox);
add(vBox);
operationListener al = new operationListener();
addButton.addActionListener(al);
subtractButton.addActionListener(al);
multiplyButton.addActionListener(al);
divideButton.addActionListener(al);
}
private class operationListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String op1 = operand1.getText();
double d1;
try {
d1 = Double.parseDouble(op1);
}
catch( NumberFormatException nfe ) {
JOptionPane.showMessageDialog(null,
"First operand is not a proper number");
return;
}
String op2 = operand2.getText();
double d2;
try {
d2 = Double.parseDouble(op2);
}
catch(NumberFormatException nfe ) {
JOptionPane.showMessageDialog(null,
"Second operand is not a proper number");
return;
}
double res = 0.0;
if( ae.getSource() == addButton )
res = d1 + d2;
else if( ae.getSource() == subtractButton )
res = d1 - d2;
else if ( ae.getSource() == multiplyButton )
res = d1 * d2;
else if (ae.getSource() == divideButton )
{
if (d2 == 0) JOptionPane.showMessageDialog(null,
"Divide by zero error");
else
{JOptionPane.showMessageDialog(null,
"Divisor is " + d2 + " dividend is " + d1);
res = d1/d2;
}
}
result.setText(res + "");
}
}
}
-------------------------------------------------------------------------------
P.S. Please use very basic codes for this programe.
Question needs to be answered before 4/28/05 11:30pm...and it will be
deleted if not answered. |