Reputation: 81
I have 3 test fields for input and calculation result. 4 buttons for the math operations and a action listener for each one. I have a if statement to check which button i'm pressing but its not working and only the divide will work.
aa.java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class aa extends Applet implements ActionListener
{
int c;
TextField text1,text2,text3;
Button button1,button2,button3,button4;
public void init()
{
text1 = new TextField(20);
add(text1);
text2 = new TextField(20);
add(text2);
text3 = new TextField(20);
add(text3);
button1 = new Button("add");
add(button1);
button1.addActionListener(this);
button2 = new Button("sub");
add(button2);
button2.addActionListener(this);
button3 = new Button("multiply");
add(button3);
button3.addActionListener(this);
button4 = new Button("divide");
add(button4);
button4.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String str=e.getActionCommand();
int a=Integer.parseInt(text1.getText());
int b=Integer.parseInt(text2.getText());
if(str.equals("button1"))
{
c=a+b;
text3.setText(""+c);
}
else if(str.equals("button2"))
{
c=a+b;
text3.setText(""+c);
}
else if(str.equals("button3"))
{
c=a*b;
text3.setText(""+c);
}
else
{
c=a/b;
text3.setText(""+c);
}
}
}
aa.html
<HTML>
<BODY>
<APPLET ALIGN="CENTER" CODE="aa.java" width = "500" height = "500"></APPLET>
</BODY>
</HTML>
Upvotes: 0
Views: 1900
Reputation: 7910
In your actionPerformed
method, you need to check for the button's actionCommand
(by default the text it was constructed with), not its name ("multiply"
rather than "button2"
). You can change a button's action command with setActionCommand
).
See this page for more details.
Upvotes: 2