Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.JFrame;
- import javax.swing.JTextField;
- import javax.swing.JButton;
- import java.awt.FlowLayout;
- import java.awt.Dimension;
- import java.awt.event.ActionListener;
- import java.awt.event.ActionEvent;
- public class Calculadora extends JFrame
- {
- private JTextField ac;
- private JTextField input;
- private JButton div;
- private JButton mul;
- private JButton res;
- private JButton sum;
- public Calculadora()
- {
- setTitle("Calculadora");
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setLayout(new FlowLayout());
- prepare();
- pack();
- }
- private void prepare(){
- Dimension size = new Dimension(45,30);
- ActionListener l = new ActionListener()
- {
- @Override
- public void actionPerformed(ActionEvent e)
- {
- double rsp = 0;
- String op = e.getActionCommand();
- switch(op){
- case SUMA :
- rsp = getAcumulador() +
- getEntrada();
- break;
- case RESTA :
- rsp = getAcumulador() -
- getEntrada();
- break;
- case MULTI :
- rsp = getAcumulador() *
- getEntrada();
- break;
- case DIVI :
- rsp = getAcumulador() /
- getEntrada();
- break;
- }
- ac.setText(Double.toString(rsp));
- }
- };
- ac = new JTextField("0.0");
- input = new JTextField();
- mul = new JButton(MULTI);
- div = new JButton(DIVI);
- res = new JButton(RESTA);
- sum = new JButton(SUMA);
- mul.setActionCommand(MULTI);
- div.setActionCommand(DIVI);
- res.setActionCommand(RESTA);
- sum.setActionCommand(SUMA);
- mul.addActionListener(l);
- div.addActionListener(l);
- res.addActionListener(l);
- sum.addActionListener(l);
- ac.setPreferredSize(size);
- input.setPreferredSize(size);
- mul.setPreferredSize(size);
- div.setPreferredSize(size);
- res.setPreferredSize(size);
- sum.setPreferredSize(size);
- ac.setEnabled(false);
- add(ac);
- add(input);
- add(sum);
- add(res);
- add(mul);
- add(div);
- }
- private double getAcumulador()
- {
- return Double.parseDouble(ac.getText());
- }
- private double getEntrada()
- {
- return Double.parseDouble(input.getText());
- }
- private static final String SUMA = "+";
- private static final String RESTA = "-";
- private static final String MULTI = "*";
- private static final String DIVI = "/";
- public static void main(String[] args)
- {
- (new Calculadora()).setVisible(true);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement