0% found this document useful (0 votes)
22 views3 pages

Swing Calculatrice Java

Download as odt, pdf, or txt
Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1/ 3

Les lourdes programme Swing en Java :

1-Calculatrice :

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class Calculatrice extends JFrame implements ActionListener {


JButton b10, b11, b12, b13, b14, b15;
JButton b[] = new JButton[10];
int i, r, n1, n2;
JTextField res;
char op;

public Calculatrice() {
super("Calculatrice");
setLayout(new BorderLayout());

JPanel p = new JPanel();


p.setLayout(new GridLayout(4, 4));

for (i = 0; i <= 9; i++) {


b[i] = new JButton(Integer.toString(i));
p.add(b[i]);
b[i].addActionListener(this);
}

b10 = new JButton("+");


p.add(b10);
b10.addActionListener(this);

b11 = new JButton("-");


p.add(b11);
b11.addActionListener(this);

b12 = new JButton("*");


p.add(b12);
b12.addActionListener(this);

b13 = new JButton("/");


p.add(b13);
b13.addActionListener(this);

b14 = new JButton("=");


p.add(b14);
b14.addActionListener(this);
b15 = new JButton("C");
p.add(b15);
b15.addActionListener(this);

res = new JTextField(10);

add(p, BorderLayout.CENTER);
add(res, BorderLayout.NORTH);

setVisible(true);
setSize(200, 200);
}

public void actionPerformed(ActionEvent ae) {


JButton pb = (JButton) ae.getSource();

if (pb == b15) {
r = n1 = n2 = 0;
res.setText("");
} else if (pb == b14) {
n2 = Integer.parseInt(res.getText());
eval();
res.setText(Integer.toString(r));
} else {
boolean opf = false;

if (pb == b10) {
op = '+';
opf = true;
}
if (pb == b11) {
op = '-';
opf = true;
}
if (pb == b12) {
op = '*';
opf = true;
}
if (pb == b13) {
op = '/';
opf = true;
}

if (!opf) {
for (i = 0; i < 10; i++) {
if (pb == b[i]) {
String t = res.getText();
t += i;
res.setText(t);
}
}
} else {
n1 = Integer.parseInt(res.getText());
res.setText("");
}
}
}

int eval() {
switch (op) {
case '+':
r = n1 + n2;
break;
case '-':
r = n1 - n2;
break;
case '*':
r = n1 * n2;
break;
case '/':
r = n1 / n2;
break;
}
return 0;
}

public static void main(String arg[]) {


new Calculatrice();
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy