Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.JFrame;
- import javax.swing.Action;
- import javax.swing.JButton;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- import java.awt.GridLayout;
- import javax.swing.JOptionPane;
- import java.awt.TextField;
- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- import java.awt.event.MouseAdapter;
- import java.awt.event.MouseEvent;
- public class Calcolatrice extends JFrame{
- private JButton[] numeri = new JButton[12];
- private JButton[] operatori = new JButton[4];
- private TextField casellaDiCalcolo = new TextField();
- private String stampa = "";
- public Calcolatrice(){
- setVisible(true);
- setSize(500,500);
- setLayout(new GridLayout(3,1));
- add(casellaDiCalcolo);
- add(new TabNumeri());
- add(new TabOperatori());
- addMouseListener(new AscoltatoreMouse());
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- }//Calcolatrice
- class AscoltatoreMouse extends MouseAdapter{
- private double op1 = 0;
- private double op2 = 0;
- private boolean isOp2 = false;
- private String operatore = "+";
- public void mousePressed(MouseEvent e){
- JButton bottoneMagico;
- if(e.getComponent() instanceof JButton) {
- bottoneMagico = (JButton)e.getComponent();
- if(Character.isDigit(bottoneMagico.getText().charAt(0)))
- casellaDiCalcolo.setText(casellaDiCalcolo.getText()+bottoneMagico.getText());
- else {
- operatore = bottoneMagico.getText();
- if(isOp2) {
- op2 = Double.parseDouble(casellaDiCalcolo.getText());
- } else {
- op1 = Double.parseDouble(casellaDiCalcolo.getText());
- }
- casellaDiCalcolo.setText("");
- isOp2 = !isOp2;
- if(bottoneMagico.getText() == "=") {
- if(operatore == "+") casellaDiCalcolo.setText(""+(op1 + op2));
- if(operatore == "-") casellaDiCalcolo.setText(""+(op1 - op2));
- if(operatore == "*") casellaDiCalcolo.setText(""+(op1 * op2));
- if(operatore == "/") casellaDiCalcolo.setText(""+(op1 / op2));
- }
- }
- }//if
- }//mousePressed
- }//AscoltatoreMouse
- class TabNumeri extends JPanel{
- public TabNumeri(){
- setLayout(new GridLayout(4,3));
- for(int i=9;i>-1;i--){
- numeri[i] = new JButton(""+i);
- add(numeri[i]);
- }//for
- numeri[10] = new JButton("=");
- add(numeri[10]);
- numeri[11] = new JButton(".");
- add(numeri[11]);
- }//TabNumeri
- }//TabNumeri
- class TabOperatori extends JPanel{
- public TabOperatori(){
- setLayout(new GridLayout(1,4));
- operatori[0] = new JButton("/");
- add(operatori[0]);
- operatori[1] = new JButton("*");
- add(operatori[1]);
- operatori[2] = new JButton("-");
- add(operatori[2]);
- operatori[3] = new JButton("+");
- add(operatori[3]);
- }//TabOperatori
- }//TabOperatori
- }//Calcolatrice
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement