I need to write a program with a combo box, where the items in the combo box wil
ID: 3720964 • Letter: I
Question
I need to write a program with a combo box, where the items in the combo box will Add, Subtract, multiply, and divide. I have these already stated in combo box but have no idea how to write it so it takes effect in the program. What do I need to do so it actually adds when suppose to and subtract. I need to write a program with a combo box, where the items in the combo box will Add, Subtract, multiply, and divide. I have these already stated in combo box but have no idea how to write it so it takes effect in the program. What do I need to do so it actually adds when suppose to and subtract.Explanation / Answer
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.invoke.SwitchPoint;
import javax.swing.*;
public class Calculate extends JFrame implements ActionListener{
private String[] operation = { "+", "-", "*", "/","%"};
private JTextField n1,n2;
private JComboBox cb;
private JButton bt,net;
private JLabel l,l2;
public Calcule(){
bt = new JButton("calculate");
bt.addActionListener(this);
n1 = new JTextField(10);
n2 = new JTextField(10);
l=new JLabel("Result = ");
cb = new JComboBox(operation);
l2 = new JLabel("0");
net = new JButton("Net");
net.addActionListener(this);
JPanel p = new JPanel();
p.add(n1);
p.add(cb);
p.add(n2);
p.add(bt);
p.add(l);
p.add(l2);
p.add(net);
this.setContentPane(p);
this.setTitle("Calculator");
this.setSize(300,200);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
float s;
int v1=Integer.parseInt(n1.getText());
int v2=Integer.parseInt(n2.getText());
if(e.getSource()==bt){
switch ((String)cb.getSelectedItem())
{
case "+":
s = v1+v2;
l2.setText(""+s);
break;
case "*":
s = v1*v2;
l2.setText(""+s);
break;
case "-":
s = v1-v2;
l2.setText(""+s);
break;
case "/":
s = v1/v2;
l2.setText(""+s);
break;
case "%":
s = v1%v2;
l2.setText(""+s);
break;
}
}
if(e.getSource()==net){
n1.setText("");
n2.setText("");
l2.setText("0");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Calculate();
}
}