This commit is contained in:
2025-11-06 09:36:30 +01:00
parent 72a5882f3f
commit 4ca42b835c
12 changed files with 348 additions and 0 deletions

View File

@@ -0,0 +1,79 @@
package calc;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
class ButtonHandler implements ActionListener {
JTextField tf;
int a,b;
String op;
public ButtonHandler(JTextField tf) {
this.tf = tf;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("+") || e.getActionCommand().equals("-")) {
op = e.getActionCommand();
a = Integer.parseInt(tf.getText());
tf.setText("");
return;
}
if (e.getActionCommand().equals("=")) {
b = Integer.parseInt(tf.getText());
if(op.equals("+")) tf.setText(""+(a+b));
if(op.equals("-")) tf.setText(""+(a-b));
return;
}
tf.setText(tf.getText()+e.getActionCommand());
}
}
// Classe principale con il metodo main
public class CalcolatriceMain {
public static void main(String[] args) {
JFrame f = new JFrame("titolo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBounds(100, 100, 300, 500);
f.setLayout(null);
JTextField tf = new JTextField("0");
tf.setBounds(10, 10, 240, 80);
f.add(tf);
ButtonHandler bh = new ButtonHandler(tf);
int x = 10;
int y = 100;
int cont = 1;
for (int j = 0; j < 3; j++) {
for (int i = 0; i < 3; i++) {
JButton bn = new JButton("" + cont);
bn.setActionCommand("" + cont);
bn.setBounds(x, y, 80, 80);
f.add(bn);
x += 80;
bn.addActionListener(bh);
cont++;
}
y += 80;
x = 10;
}
String[] etichette = {"+","-","="};
for (int i = 0; i < 3; i++) {
JButton bn = new JButton(etichette[i]);
bn.setActionCommand(etichette[i]);
bn.setBounds(x, y, 80, 80);
f.add(bn);
x += 80;
bn.addActionListener(bh);
}
f.setVisible(true);
}
}