Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.BorderLayout;
- import java.awt.GridLayout;
- import java.awt.FlowLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.util.HashSet;
- import javax.swing.JFrame;
- import javax.swing.JButton;
- import javax.swing.JPanel;
- import javax.swing.JLabel;
- import javax.swing.JTextField;
- import javax.swing.SwingConstants;
- public class Calculadora extends JFrame implements ActionListener{
- JButton btnSoma, btnDiferenca, btnMult, btnDivide, btnClear;
- JLabel txt1, txt2, txt3;
- JTextField txtValor1, txtValor2, txtResul;
- public void actionPerformed (ActionEvent e){
- float num1, num2, resul;
- try{
- num1 = Float.parseFloat (txtValor1.getText());
- num2 = Float.parseFloat (txtValor2.getText());
- }catch (NumberFormatException erro){
- num1=0;
- num2=0;
- }
- if (e.getSource() == btnSoma){
- resul = num1+num2;
- txtResul.setText(String.format("%5.2f", resul));
- }
- else if (e.getSource()==btnDiferenca){
- resul = num1-num2;
- txtResul.setText(String.format("%5.2f", resul));
- }
- else if (e.getSource()== btnDivide){
- resul = num1 / num2;
- txtResul.setText (String.format("%5.2f", resul));
- }
- else if (e.getSource() == btnMult){
- resul = num1 * num2;
- txtResul.setText (String.format("%5.2f", resul));
- }
- else{
- txtValor1.setText("");
- txtValor2.setText("");
- txtResul.setText("");
- }
- }
- public Calculadora(){
- setLayout (new BorderLayout());
- btnSoma = new JButton ("+");
- btnDiferenca = new JButton ("-");
- btnDivide = new JButton ("/");
- btnMult = new JButton ("x");
- btnClear = new JButton ("Clear");
- JPanel leste = new JPanel (new GridLayout (5,1));
- leste.add(btnSoma);
- leste.add(btnDiferenca);
- leste.add(btnDivide);
- leste.add(btnMult);
- leste.add(btnClear);
- add (leste, BorderLayout.EAST);
- JPanel centro = new JPanel (new GridLayout (3,2));
- txt1 = new JLabel ("Entre com o valor 1 :", SwingConstants.RIGHT);
- txt2 = new JLabel ("Entre com o valor 2 :", SwingConstants.RIGHT);
- txt3 = new JLabel ("Resultado :", SwingConstants.RIGHT);
- txtValor1 = new JTextField (5);
- txtValor2 = new JTextField (5);
- txtResul = new JTextField (5);
- centro.add (txt1);
- centro.add (txtValor1);
- centro.add (txt2);
- centro.add (txtValor2);
- centro.add (txt3);
- centro.add (txtResul);
- add (centro, BorderLayout.CENTER);
- btnSoma.addActionListener(this);
- btnDiferenca.addActionListener(this);
- btnMult.addActionListener(this);
- btnDivide.addActionListener(this);
- btnClear.addActionListener(this);
- }
- public static void main (String [] args){
- Calculadora tela = new Calculadora ();
- tela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- tela.setSize (350,250);
- tela.setLocation (500,300);
- tela.setVisible(true);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment