Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // https://www.facebook.com/groups/JavaBr/permalink/13271875172
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- public class Exemplo0505 extends JFrame implements ActionListener {
- private static final long serialVersionUID = 1L;
- JLabel L1, L2, L3;
- JButton B1, B2, B3, B4, B5;
- JTextField T1, T2, T3;
- public static void main(String args[]) {
- JFrame Janela = new Exemplo0505();
- Janela.setVisible(true);
- WindowListener x = new WindowAdapter() {
- // você precisa sobrescrever algum método
- // System.exit(0);
- };
- Janela.addWindowListener(x);
- }
- Exemplo0505() {
- setTitle("calculadora");
- setSize(350, 90);
- setLocation(50, 50);
- getContentPane().setBackground(new Color(150, 150, 150));
- getContentPane().setLayout(new GridLayout(3, 4));
- L1 = new JLabel("num1");
- L1.setForeground(Color.black);
- L2 = new JLabel("num2");
- L2.setForeground(Color.black);
- L2.setFont(new Font("", Font.BOLD, 14));
- L3 = new JLabel("total");
- L3.setFont(new Font("", Font.BOLD, 14));
- B1 = new JButton("+");
- B1.addActionListener(this);
- B2 = new JButton("-");
- B2.addActionListener(this);
- B3 = new JButton("*");
- B3.addActionListener(this);
- B4 = new JButton("/");
- B4.addActionListener(this);
- B5 = new JButton("LImPAR");
- B5.addActionListener(this);
- B5.setBackground(Color.black);
- B5.setForeground(Color.white);
- T1 = new JTextField();
- T2 = new JTextField();
- T3 = new JTextField();
- getContentPane().add(L1);
- getContentPane().add(T1);
- getContentPane().add(B1);
- getContentPane().add(L2);
- getContentPane().add(T2);
- getContentPane().add(B2);
- getContentPane().add(L3);
- getContentPane().add(T3);
- getContentPane().add(B3);
- getContentPane().add(B4);
- getContentPane().add(B5);
- }
- public void actionperformed(ActionEvent e) {
- if (e.getSource() == B5) {
- T1.setText("");
- T2.setText("");
- T3.setText("");
- return;
- }
- Float N1 = 0f, N2 = 0f, result = 0f;
- try {
- N1 = Float.parseFloat(T1.getText());
- N2 = Float.parseFloat(T2.getText());
- } catch (NumberFormatException Error) {
- T3.setText("Erro");
- return;
- }
- if (e.getSource() == B1) {
- result = N1 + N2;
- } else if (e.getSource() == B2) {
- result = N1 - N2;
- } else if (e.getSource() == B3) {
- result = N1 * N2;
- } else if (e.getSource() == B4) {
- result = N1 / N2;
- }
- T3.setText("" + result);
- }
- @Override
- public void actionPerformed(ActionEvent e) {
- // faltava implementar esse método, mas pq essa classe é um
- // actionlistener?
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment