Calculadora

Fala galera, blz ?

Então, enfim me solicitaram a criação da calculadora na facul, porém estou tendo um pouco de dificuldade pra organizar os botões, campos e etc…segue o código:


import java.awt.GridLayout;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Calculadora extends JFrame implements ActionListener
{
	private JButton buttons[]; // array de botões
	private final String names[] = { "1","2","3","+","C","4","5","6","-","CE","7"
											  ,"8","9","*","RAIZ","+/-","0",".","/","="};
	private boolean toggle = true; // alterna entre dois layouts
	private Container container; // contêiner do frame
	private GridLayout gridLayout1; // primeiro gridlayout
	private GridLayout gridLayout2; // segundo gridlayout
	private JTextField texto;
	
	// construtor sem argumento
	public Calculadora()
	{
		super( "GridLayout Demo" );
		gridLayout1 = new GridLayout( 4, 5 , 2, 2); // 2 por 3; lacunas de 5
		container = getContentPane(); // obtém painel de conteúdo
		setLayout( gridLayout1 ); // configura o layout JFrame
		buttons = new JButton[ names.length ]; // cria array de JButtons
		texto = new JTextField(20);
		
		for ( int count = 0; count < names.length; count++ )
		{
			buttons[ count ] = new JButton( names[ count ] );
			buttons[ count ].addActionListener( this ); // registra o listener
			add( buttons[ count ] ); // adiciona o botão ao JFrame
		} // for final
	} // fim do construtor GridLayoutFrame

	// trata eventos de botão alternando entre layouts
	public void actionPerformed( ActionEvent event )
	{
		if ( toggle )
		container.setLayout( gridLayout1 ); // configura layout como segundo
		else
		container.setLayout( gridLayout1 ); // configura layout como primeiro
		toggle = !toggle; // alterna para valor oposto
		container.validate(); // refaz o layout do contêiner
	} // fim do método actionPerformed
} // fim da classe Calculadora

a dúvida é a seguinte, como eu coloco o JTextField na parte de cima da tela pra exibir somente os valores que serão calculados, pq colocando normalmente igual eu fiz no código, ele fica todo desordenado na telinha…

No aguardo,

Abs,

postei sem o JLabel, mas ja está com o JLabel e setEditable(false)…agora só preciso saber como deixo ele no topo da tela…sem ficar ao lado dos botões…

Porque vc não usa todos usando o .setlocation()
Desse modo vc pode setar a localização de todos os seus componentes. é so colocar SeuFrame.setLayout(null);
e tem que dimensionar o tamanho do frame SeuFrame.setSize(700, 250); //aqui vc coloca o tamanho do seu frame
e quando for add botões ou qualquer outra coisa vc usa botao.setLocation(100,50);
Espero ter ajudado.
a outra coisa bacana seria tirar a opção de maximizar iria ficar bem bacana.

cara, esse setLocation eu nunca usei, no caso ele faria oq ue ?

testei aqui e não deu certo…

[quote=digolipertte]Porque vc não usa todos usando o .setlocation()
Desse modo vc pode setar a localização de todos os seus componentes. é so colocar SeuFrame.setLayout(null);
e tem que dimensionar o tamanho do frame SeuFrame.setSize(700, 250); //aqui vc coloca o tamanho do seu frame
e quando for add botões ou qualquer outra coisa vc usa botao.setLocation(100,50);
Espero ter ajudado.
a outra coisa bacana seria tirar a opção de maximizar iria ficar bem bacana.[/quote]

Ficaria pior ainda.

Faça o seguinte: set o layout de seu JFrame para BorderLayout e adicione seu JTextField na posição NORT (jframe.add(jtextfield, BorderLayout.NORT), depois adicione um JPanel na posição CENTER do seu JFrame (jframe.add(jpanel, BorderLayout.CENTER) e set o layout do JPanel para GridLayout(qt de linhas desejadas, qt de colunas desejadas) e adicione os botões neste JPanel (jpanel.add(jbutton).

:thumbup:

farei as alterações e postarei aqui o resultado Henrique, obrigado! :smiley:

De nada :smiley:

:thumbup:

Henrique, deu certo cara…só me explica essa parte pq eu não entendi direito e acabei fazendo bosta…

"e set o layout do JPanel para GridLayout(qt de linhas desejadas, qt de colunas desejadas) e adicione os botões neste JPanel (jpanel.add(jbutton). "

como ficaria isso ?

pra utilizar o border e o grid na mesma tela eu vou ter que criar 2 classes e fazer um extend ?

confundiu tudo agora…rsrs

abs

Não. Cada contêiner Swing aceita um gerenciador de layout diferente, assim você pode “combinar” vários layout em uma tela.

Segue um exemplo, só a montagem da tela, os eventos e funcionalidades ficaram por sua conta :smiley:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 * @author Henrique Ferreira da Silva
 */
public class Calculadora extends JFrame {

    private final String names[] = {"1", "2", "3", "+", "C", "4", "5", "6", "-", "CE", "7", "8", "9", "*", "RAIZ", "+/-", "0", ".", "/", "="};

    public Calculadora() {
        /*
         * Por padrão, o gerenciador de layout do JFrame é BorderLayout.
         * Adicionamos um novo JTextField na posição norte do JFrame.
         */
        add(new JTextField(), BorderLayout.NORTH);
        /*
         * Por padrão, o gerenciador de layout do JPanel é FlowLayout. Porém,
         * adicionamos um novo JPanel e alteramos seu gerenciador de layout para
         * GridLayout, com 4 linhas, 6 colunas, 5 em espaçamento horizontal e 5
         * em espaçamento vertical entre os componentes.
         */
        JPanel painel = new JPanel(new GridLayout(4, 6, 5, 5));
        for (byte i = 0; i < 20; i++) {
            /**
             * Adicionamos 1 botão em cada célula do GridLayout do painel, da
             * seguinte maneira: 1º botão na 1º linha da 1º coluna, 2º botão na
             * 1º linha da 2º coluna, 3º botão na 1º linha da 3º coluna, e assim
             * por diante, até completar todas as colunas de cada linha.
             */
            painel.add(new JButton(names[i]));
        }
        /**
         * Adicionamos o painel no JFrame, este painel irá preencher todos os
         * espaços restantes do BorderLayout, são eles BorderLayout.CENTER,
         * BorderLayout.EAST, BorderLayout.WEST e BorderLayout.SOUTH.
         */
        add(painel);
        setTitle("Calculadora");
        setSize(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        new Calculadora().setVisible(true);
    }
}

:thumbup:

Obrigado mais uma vez Henrique, pude perceber que nessa linha

add(new JTextField(), BorderLayout.NORTH); vc não deu um nome ao JText, na minha concepção era necessário fazer isso…tipo

texto = new JTextField, borde…ou posso fazer desse jeito tbm ?

Sim, eu instanciei e adicionei o JTextField de uma fez (pq era só um exemplo), mas você terá que declara-lo lá em cima:

private JTextField texto = new JTextField();

E terá que fazer isto também com os JButtons.

:thumbup:

Outra coisa, como eu vou ter que dar uma função para cada botão, tenho que criar eles individualmente, ao invés de criar um array de botões ?

Tanto faz se será um array de botão ou não, você precisará adicionar eventos em cada um deles.

:thumbup:

Henrique, vc pode me dar um exemplo de como criar a função de um botão cara, pq eu até segui uns exemplos aqui do guj msm, pesquisei um pouco e não deram certo…

qual a maneira mais fácil de fazer isso ?

abs,

na verdade eu não to sabendo como declaro a posição do array no actionPerformed…por exemplo, eu fiz assim:

public void actionPerformed(ActionEvent evento)
		{
			//JOptionPane.showMessageDialog(null, getSize());
			if(buttons[0].getSource() == buttons[0])
			{
				int valor;
				valor = Integer.parseInt(texto.getText());
				valor = buttons[0];
				texto.setText(""+valor);
			}
		} // Fecha o método actionPerformed 

[code]botao.addActionListener(new ActionListener() {

        @Override    
        public void actionPerformed(ActionEvent arg0) {    
               
        	   
              //Aqui vc coloca oque vc quer que o botão faça......
        }    
    });

[/code]
Não esqueça de colocar os imports que pode ter sido o erro dos outros exeplos. import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.*;

Se não der posta seu codigo ai pra ficar mais facil a explicação.

Opa, então digo…o código ficou assim:


import java.awt.BorderLayout;  
import java.awt.GridLayout;  
import javax.swing.JButton;  
import javax.swing.JFrame;  
import javax.swing.JPanel;  
import javax.swing.JTextField;  
import java.awt.event.ActionEvent;  
import java.awt.event.ActionListener;  
import java.awt.*;   

 
public class Calculadora extends JFrame {  
  
    private final String names[] = {"1", "2", "3", "+", "C", "4", "5", "6", "-", "CE", "7", "8", "9", "*", "RAIZ", "+/-", "0", ".", "/", "="};  
  	 JTextField texto;	 
	 
    public Calculadora() 
	 {
                
			buttons = new JButton[ names.length ];
			texto = new JTextField(20);
			add(new JTextField(), BorderLayout.NORTH);  
			JPanel painel = new JPanel(new GridLayout(4, 6, 5, 5));  
					 
        
		  for (int i = 0; i < 20; i++) 
		  {          
            painel.add(new JButton(names[i]));  
        }  
       
        add(painel);  
        setTitle("Calculadora");  
        setSize(400, 400);  
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        setResizable(false);  
        setLocationRelativeTo(null);  
    }  
  
  		buttons[i].addActionListener(new ActionListener() {      
              
        @Override      
        public void actionPerformed(ActionEvent arg0) 
				{      
      	      if(buttons[0].getSource == buttons[0])
					{
						int valor;
						valor = Integer.parseInt(texto.getText());
						valor = buttons[0];  
                	texto.setText(""+valor);       
               }      
                
            }      
        }
		);  
  					
			
			  
	 
	 public static void main(String[] args) {  
        new Calculadora().setVisible(true);  
    }  
}  

A minha dúvida é:

buttons[i].addActionListener(new ActionListener() {      
              
        @Override      
        public void actionPerformed(ActionEvent arg0) 
				{      
      	      if(buttons[0].getSource == buttons[0])
					{
						int valor;
						valor = Integer.parseInt(texto.getText());
						valor = buttons[0];  
                	texto.setText(""+valor);       
               }      
                
            }      
        }
		);  

Como eu criei um array de botões, como eu defino esse botão ali no ActionListener, pois no caso acima coloquei buttons[0] que no caso é o meu array, mas não deu certo…pode ser uma duvida idiota, porém eu não to conseguindo :S

abs,

olha cara fiz essa como exemplo mas usei o NB para a interface

[code]//Calculadora Simples em Java para iniciantes, desenvolvida no NetBeans 7.0

public class Calculadora extends javax.swing.JFrame {

public Calculadora() {
    initComponents();
}

/Variaveis booleanas, todas estão sendo iniciadas como “false”, quando pressionar o botão “=”,
elas irão identificar qual operação será realizada
/
boolean clickSomar=false, clickSubtrair=false, clickMultiplicar=false, clickDividir=false;
//Variáveis double, armazenarão os valores digitados e o resultado da operação
double primeiroValor, segundoValor, resultado;
@SuppressWarnings(“unchecked”)
//
private void initComponents() {

    tf_exibir = new javax.swing.JTextField();
    bt_8 = new javax.swing.JButton();
    bt_7 = new javax.swing.JButton();
    bt_9 = new javax.swing.JButton();
    bt_somar = new javax.swing.JButton();
    bt_4 = new javax.swing.JButton();
    bt_5 = new javax.swing.JButton();
    bt_6 = new javax.swing.JButton();
    bt_subtrair = new javax.swing.JButton();
    bt_1 = new javax.swing.JButton();
    bt_2 = new javax.swing.JButton();
    bt_3 = new javax.swing.JButton();
    bt_multiplicar = new javax.swing.JButton();
    bt_zero = new javax.swing.JButton();
    bt_decimal = new javax.swing.JButton();
    bt_igual = new javax.swing.JButton();
    bt_dividir = new javax.swing.JButton();
    bt_limpar = new javax.swing.JButton();
    bt_sair = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    tf_exibir.setEditable(false);
    tf_exibir.setFont(new java.awt.Font("Digital Readout Upright", 0, 36)); // NOI18N
    tf_exibir.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
    tf_exibir.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            tf_exibirActionPerformed(evt);
        }
    });

    bt_8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    bt_8.setText("8");
    bt_8.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_8ActionPerformed(evt);
        }
    });

    bt_7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    bt_7.setText("7");
    bt_7.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_7ActionPerformed(evt);
        }
    });

    bt_9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    bt_9.setText("9");
    bt_9.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_9ActionPerformed(evt);
        }
    });

    bt_somar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    bt_somar.setText("+");
    bt_somar.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_somarActionPerformed(evt);
        }
    });

    bt_4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    bt_4.setText("4");
    bt_4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_4ActionPerformed(evt);
        }
    });

    bt_5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    bt_5.setText("5");
    bt_5.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_5ActionPerformed(evt);
        }
    });

    bt_6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    bt_6.setText("6");
    bt_6.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_6ActionPerformed(evt);
        }
    });

    bt_subtrair.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    bt_subtrair.setText("-");
    bt_subtrair.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_subtrairActionPerformed(evt);
        }
    });

    bt_1.setFont(new java.awt.Font("Tahoma", 0, 14));
    bt_1.setText("1");
    bt_1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_1ActionPerformed(evt);
        }
    });

    bt_2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    bt_2.setText("2");
    bt_2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_2ActionPerformed(evt);
        }
    });

    bt_3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    bt_3.setText("3");
    bt_3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_3ActionPerformed(evt);
        }
    });

    bt_multiplicar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    bt_multiplicar.setText("x");
    bt_multiplicar.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_multiplicarActionPerformed(evt);
        }
    });

    bt_zero.setFont(new java.awt.Font("Tahoma", 0, 14));
    bt_zero.setText("0");
    bt_zero.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_zeroActionPerformed(evt);
        }
    });

    bt_decimal.setFont(new java.awt.Font("Tahoma", 0, 14));
    bt_decimal.setText(".");
    bt_decimal.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_decimalActionPerformed(evt);
        }
    });

    bt_igual.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    bt_igual.setText("=");
    bt_igual.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_igualActionPerformed(evt);
        }
    });

    bt_dividir.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    bt_dividir.setText("/");
    bt_dividir.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_dividirActionPerformed(evt);
        }
    });

    bt_limpar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    bt_limpar.setText("C");
    bt_limpar.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_limparActionPerformed(evt);
        }
    });

    bt_sair.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    bt_sair.setText("SAIR");
    bt_sair.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bt_sairActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(tf_exibir, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                    .addComponent(bt_7)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(bt_8)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(bt_9)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(bt_somar, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                    .addComponent(bt_4)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(bt_5)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(bt_6)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(bt_subtrair, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(bt_limpar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 92, Short.MAX_VALUE)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(bt_zero)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(bt_decimal, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(bt_1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(bt_2, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(bt_sair, javax.swing.GroupLayout.DEFAULT_SIZE, 92, Short.MAX_VALUE)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(bt_3)
                                .addComponent(bt_igual))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(bt_dividir, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(bt_multiplicar))))))
            .addContainerGap())
    );

    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {bt_1, bt_2, bt_3, bt_4, bt_5, bt_6, bt_7, bt_8, bt_9, bt_decimal, bt_dividir, bt_igual, bt_multiplicar, bt_somar, bt_subtrair, bt_zero});

    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(tf_exibir, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(bt_7)
                .addComponent(bt_8)
                .addComponent(bt_9)
                .addComponent(bt_somar))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(bt_4)
                .addComponent(bt_5)
                .addComponent(bt_6)
                .addComponent(bt_subtrair))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(bt_1)
                .addComponent(bt_2)
                .addComponent(bt_3)
                .addComponent(bt_multiplicar))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(bt_zero)
                .addComponent(bt_decimal)
                .addComponent(bt_igual)
                .addComponent(bt_dividir))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(bt_limpar)
                .addComponent(bt_sair))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {bt_1, bt_2, bt_3, bt_4, bt_5, bt_6, bt_7, bt_8, bt_9, bt_decimal, bt_dividir, bt_igual, bt_multiplicar, bt_somar, bt_subtrair, bt_zero});

    pack();
}// </editor-fold>                        

//Ações dos botões
private void bt_zeroActionPerformed(java.awt.event.ActionEvent evt) {
tf_exibir.setText(tf_exibir.getText()+bt_zero.getText());
/tf_exibir=nome do JTextField
bt_zero=nome do Jbutton
.setText=comando para exibir conteúdo no JTextField
.getText=comando que captura o texto do componente (“bt_zero” o texto está como 0)
/
}

private void bt_decimalActionPerformed(java.awt.event.ActionEvent evt) {
tf_exibir.setText(tf_exibir.getText()+bt_decimal.getText()); /Para operações decimais deve-se usar o ponto “.”,
atenção para não confundir com a vírgula “,”,
pois as operações não irão funcionar
/
}

private void bt_1ActionPerformed(java.awt.event.ActionEvent evt) {
tf_exibir.setText(tf_exibir.getText()+bt_1.getText());
}

private void tf_exibirActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

private void bt_2ActionPerformed(java.awt.event.ActionEvent evt) {
tf_exibir.setText(tf_exibir.getText()+bt_2.getText());
}

private void bt_3ActionPerformed(java.awt.event.ActionEvent evt) {
tf_exibir.setText(tf_exibir.getText()+bt_3.getText());
}

private void bt_4ActionPerformed(java.awt.event.ActionEvent evt) {
tf_exibir.setText(tf_exibir.getText()+bt_4.getText());
}

private void bt_5ActionPerformed(java.awt.event.ActionEvent evt) {
tf_exibir.setText(tf_exibir.getText()+bt_5.getText());
}

private void bt_6ActionPerformed(java.awt.event.ActionEvent evt) {
tf_exibir.setText(tf_exibir.getText()+bt_6.getText());
}

private void bt_7ActionPerformed(java.awt.event.ActionEvent evt) {
tf_exibir.setText(tf_exibir.getText()+bt_7.getText());
}

private void bt_8ActionPerformed(java.awt.event.ActionEvent evt) {
tf_exibir.setText(tf_exibir.getText()+bt_8.getText());
}

private void bt_9ActionPerformed(java.awt.event.ActionEvent evt) {
tf_exibir.setText(tf_exibir.getText()+bt_9.getText());
}

private void bt_somarActionPerformed(java.awt.event.ActionEvent evt) {
capturar(); //executa o método capturar, POO, ver método abaixo
tf_exibir.setText(""); //no JTextField será exibido um valor vazio (""), para melhor visualização
clickSomar=true;/* a variavel do tipo booleana recebe o valor “true” (verdadeiro), então identificamos
a operação como sendo uma soma.*/
}

private void bt_subtrairActionPerformed(java.awt.event.ActionEvent evt) {
capturar();
tf_exibir.setText("");
clickSubtrair=true;
}

private void bt_multiplicarActionPerformed(java.awt.event.ActionEvent evt) {
capturar();
tf_exibir.setText("");
clickMultiplicar=true;
}

private void bt_dividirActionPerformed(java.awt.event.ActionEvent evt) {
capturar();
tf_exibir.setText("");
clickDividir=true;
}

private void bt_igualActionPerformed(java.awt.event.ActionEvent evt) {
segundoValor=(Double.parseDouble(tf_exibir.getText()));/a variável do tipo double recebe o valor do JTextField,
como o valor é do tipo string, é necessário converter
para double (Double.parseDouble(“insira aqui o que você
irá converter de string para double”))
/

/Identifica qual operação será realizada, a variável boolena é responsável por essa identificação/
if(clickSomar)
{
resultado=primeiroValor+segundoValor; //Executa a respectiva operação, neste caso, será uma soma.
exibirResultado();//Executa o método, POO, ver detalhes abaixo.
clickSomar=false;/A variável recebe novamento o valor “false”, deixando a calculadora livre para receber outra
operaçao
/
}
else if(clickSubtrair)
{
resultado=primeiroValor-segundoValor;
exibirResultado();
clickSubtrair=false;
}

else if(clickMultiplicar)
{
resultado=primeiroValor*segundoValor;
exibirResultado();
clickMultiplicar=false;
}

 //Tratamento de erro de divisões por zero, impossíveis. 
 else
{
  if(segundoValor==0) //se o segundo valor for igual a zero
  {
  tf_exibir.setText("ERRO");//Exibir "ERRO", pois a operação não é possível
  }
  else // caso o segundo valor for diferente de zero
    {
      resultado=primeiroValor/segundoValor; //Executa a operação como os exemplos acima.
      exibirResultado();
    }
  clickDividir=false;
}

}

private void bt_limparActionPerformed(java.awt.event.ActionEvent evt) {
tf_exibir.setText("");//Limpa o JTextField (tf_exibir), inserindo um valor vazio “”.
}

private void bt_sairActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);//Comando para fechar a aplicação
}

void capturar()
{
primeiroValor=(Double.parseDouble(tf_exibir.getText()));
//a variável do tipo double recebe o valor do JTextField, como o valor é do tipo string, é necessário converter
// para double (Double.parseDouble(“insira aqui o que você irá converter de string para double”))
}

void exibirResultado()
{
tf_exibir.setText(String.valueOf(resultado));/Exibe o resultado da operação;
como a variável “resultado” é do tipo double, deveremos converte-la
para string, pois o JTextField (tf_exibir) aceita apenas string;
o comando utilizado será o “String.valueOf(“insira a variável que
será convertida de double para string”)”
/
}

public static void main(String args[]) {
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new Calculadora().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JButton bt_1;
private javax.swing.JButton bt_2;
private javax.swing.JButton bt_3;
private javax.swing.JButton bt_4;
private javax.swing.JButton bt_5;
private javax.swing.JButton bt_6;
private javax.swing.JButton bt_7;
private javax.swing.JButton bt_8;
private javax.swing.JButton bt_9;
private javax.swing.JButton bt_decimal;
private javax.swing.JButton bt_dividir;
private javax.swing.JButton bt_igual;
private javax.swing.JButton bt_limpar;
private javax.swing.JButton bt_multiplicar;
private javax.swing.JButton bt_sair;
private javax.swing.JButton bt_somar;
private javax.swing.JButton bt_subtrair;
private javax.swing.JButton bt_zero;
private javax.swing.JTextField tf_exibir;
// End of variables declaration                   

}[/code]

Riquinho, agradeço a tentativa de ajudar, só que…como eu to utilizando o Jgrasp pra desenvolver essa calculadora, esse seu código me deixo ainda mais confuso…pq no caso,

eu estou com dúvida somente naquela parte que postei anteriormente, como eu faço pra dar função a cada botão…;(