Acão no JButton
Já li em varios tutorias em varios lugares não estou conseguindo colocar ações no meu botão quem tiver a boa vontande de olha meu código e me da uma luz de como fazer eu ficarei grato..!
bem eu já sei criar os botões e criar a classe :
private class Botao implements ActionListener
para dar acçao ao botão mas não estou conseguindo...! irei colocar o código para que vcs possam verificar..!
classe do método main
classe da GUI
Alguém me ajude meu objetivo agora e somente mostrar o número que o usuário clico no display..! eu já criei um JTextFiled como display, mas não coseguido colocar o que o usuário dígito dentro desse JTextField alguém k sabe pode me explica como faz isso..? de principio meu objetico e dar função ao botão e passar para o display..!
import javax.swing.JFrame;
public class Calculadoramain
{
public static void main(String[] args)
{
Calculadora chama = new Calculadora();
chama.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
chama.setVisible(true);
chama.setSize(500,500);
}
}
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Calculadora extends JFrame
{
private JTextField texto;
private JButton zero;
private JButton um;
private JButton dois;
private JButton tres;
private JButton quatro;
private JButton cinco;
private JButton seis;
private JButton sete;
private JButton oito;
private JButton nove;
public Calculadora()
{
super("Calculadora");
setLayout(new FlowLayout());//criar layout
texto = new JTextField(10);
add(texto);
zero=new JButton("0");
add(zero);
um=new JButton("1");
add(um);
dois=new JButton("2");
add(dois);
tres=new JButton("3");
add(tres);
quatro=new JButton("4");
add(quatro);
cinco=new JButton("5");
add(cinco);
seis=new JButton("6");
add(seis);
sete=new JButton("7");
add(sete);
oito=new JButton("8");
add(oito);
nove=new JButton("9");
add(nove);
Botao acao = new Botao();
zero.addActionListener(acao);
um.addActionListener(acao);
dois.addActionListener(acao);
tres.addActionListener(acao);
quatro.addActionListener(acao);
cinco.addActionListener(acao);
seis.addActionListener(acao);
sete.addActionListener(acao);
oito.addActionListener(acao);
}//fim do método construtor
private class Botao implements ActionListener
{
// trata evento de botão
public void actionPerformed( ActionEvent event )
{
} // fim do método actionPerformed
}
}
Edymrex
Curtidas 0
Respostas
Rodrigo Silva
09/04/2009
um exemplo mais fácil:
import javax.swing.JOptionPane;
public class Exemplo extends javax.swing.JFrame {
private javax.swing.JButton botao1;
private javax.swing.JButton botao2;
private javax.swing.JButton botao3;
private javax.swing.JButton botao4;
public Exemplo() {
initComponents();
}
private void initComponents() {
botao1 = new javax.swing.JButton();
botao2 = new javax.swing.JButton();
botao3 = new javax.swing.JButton();
botao4 = new javax.swing.JButton();
getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.X_AXIS));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
botao1.setText("INFO");
botao1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botao1ActionPerformed(evt);
}
});
getContentPane().add(botao1);
botao2.setText("WARNING");
botao2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botao2ActionPerformed(evt);
}
});
getContentPane().add(botao2);
botao3.setText("ERROR");
botao3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botao3ActionPerformed(evt);
}
});
getContentPane().add(botao3);
botao4.setText("CONFIRM");
botao4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botao4ActionPerformed(evt);
}
});
getContentPane().add(botao4);
pack();
}
private void botao4ActionPerformed(java.awt.event.ActionEvent evt) {
int i = JOptionPane.showConfirmDialog( this, "Confirmação",
"Titulo", JOptionPane.YES_NO_CANCEL_OPTION );
}
private void botao3ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog( this, "Mensagem de Erro",
"Action...", JOptionPane.ERROR_MESSAGE);
}
private void botao2ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog( this, "Mensagem de Aviso",
"Action...", JOptionPane.WARNING_MESSAGE);
}
private void botao1ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog( this, "Mensagem de Informação",
"Action...", JOptionPane.INFORMATION_MESSAGE);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Exemplo().setVisible(true);
}
});
}
}GOSTEI 0
Rodrigo Silva
09/04/2009
e?
GOSTEI 0
Ricardo Staroski
09/04/2009
private class Botao implements ActionListener {
// trata evento de botão
public void actionPerformed( ActionEvent event ) {
// sabemos que neste exemplo são somente os botões
// que vão disparar este evento neste listener
JButton botao = (JButton) event.getSource();
String texto = botao.getText();
System.out.println("Botao clicado: " + texto);
} // fim do método actionPerformed
}
GOSTEI 0
Bruno Batista
09/04/2009
Pessoal sou iniciante em java.
Uso netbeans.
gostaria de uma orientação de vocês.
tenho esse meu programa para armazenamento de dados de clientes.
caso possivel me ajudem a compila-lo.
tenho muitas duvidas.
package programabruno;
import javax.swing.*;
public class ClientesContas extends javax.swing.JFrame {
/** Creates new form ClientesContas */
public ClientesContas() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
menuSair = new javax.swing.JButton();
botaocliente = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
menuopcoes = new javax.swing.JMenu();
menuInformacoes = new javax.swing.JMenuItem();
menuEditar = new javax.swing.JMenu();
menuEditarcliente = new javax.swing.JMenuItem();
menuExibir = new javax.swing.JMenu();
menuBuscarcliente = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
menuSair.setText("Sair");
menuSair.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuSairActionPerformed(evt);
}
});
botaocliente.setText("Novo Cliente");
botaocliente.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botaoclienteActionPerformed(evt);
}
});
menuopcoes.setText("Opções");
menuInformacoes.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK));
menuInformacoes.setText("Informações do Sistema");
menuInformacoes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuInformacoesActionPerformed(evt);
}
});
menuopcoes.add(menuInformacoes);
jMenuBar1.add(menuopcoes);
menuEditar.setText("Editar");
menuEditarcliente.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
menuEditarcliente.setText("Editar Cliente");
menuEditar.add(menuEditarcliente);
jMenuBar1.add(menuEditar);
menuExibir.setText("Exibir");
menuBuscarcliente.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.CTRL_MASK));
menuBuscarcliente.setText("Buscar Cliente");
menuExibir.add(menuBuscarcliente);
jMenuBar1.add(menuExibir);
setJMenuBar(jMenuBar1);
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(339, Short.MAX_VALUE)
.addComponent(menuSair)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(botaocliente)
.addContainerGap(297, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(botaocliente)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 211, Short.MAX_VALUE)
.addComponent(menuSair)
.addContainerGap())
);
pack();
}// </editor-fold>
private void menuInformacoesActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null,"Programa Desenvolvido por Bruno Pinto.");
}
private void menuSairActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void botaoclienteActionPerformed(java.awt.event.ActionEvent evt) {
String vet[]= new String[3];
vet[1]=(JOptionPane.showInputDialog("Nome: "));
vet[2]=(JOptionPane.showInputDialog("Endereço: "));
vet[3]=(JOptionPane.showInputDialog("Empresa: "));
JOptionPane.showMessageDialog(null,"Cliente: "+ vet[1]);
JOptionPane.showMessageDialog(null,"Endereço: "+ vet[2]);
JOptionPane.showMessageDialog(null,"Empresa: "+ vet[3]);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ClientesContas().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton botaocliente;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem menuBuscarcliente;
private javax.swing.JMenu menuEditar;
private javax.swing.JMenuItem menuEditarcliente;
private javax.swing.JMenu menuExibir;
private javax.swing.JMenuItem menuInformacoes;
private javax.swing.JButton menuSair;
private javax.swing.JMenu menuopcoes;
// End of variables declaration
}
GOSTEI 0
Ricardo Staroski
09/04/2009
Bem vindo ao fórum!
Primeiramente, peço que crie um novo tópico quando sua dúvida não for pertinente ao tópico atual.
Este tópico aqui por exemplo é referente ao tratamento de eventos com um JButton.
E o seu texto não tem nada a ver com isso, OK?
[quote="brunopinto"]Uso netbeans.
Ninguém é perfeito... HeHeHe
Brincadeira, só acho que como sendo um iniciante, deveria tentar fazer alguns exemplos simples com um editor de texto e o compilador Java.
Depois de entender como a coisa funciona, aí sim começaria a experimentar uma IDE
[quote="brunopinto"]caso possivel me ajudem a compila-lo.GOSTEI 0
Blaine
09/04/2009
Off-topic:
O cara ressucitou o tópico só pra tirar um barato da cara do outro? o.O
GOSTEI 0
Bruno Batista
09/04/2009
Bom, ajudou bastante.
não axei que foi pra tirar barato*
estou compilando direto apartir de um "Novo formulario JFrame"
mandei o codigo fonte completo.
a duvida e que coloquei o JButton para adicionar novo cliente.
com a entrada de dados "Nome, Endereço, e empresa."
Mais não sei como faço pra chamar esse private.
PS: isso é se da pra chamar.
essa e a maior duvida.
caso possa ajudar, agradesço.
private void botaoclienteActionPerformed(java.awt.event.ActionEvent evt) {
String vet[]= new String[3];
vet[1]=(JOptionPane.showInputDialog("Nome: "));
vet[2]=(JOptionPane.showInputDialog("Endereço: "));
vet[3]=(JOptionPane.showInputDialog("Empresa: "));
JOptionPane.showMessageDialog(null,"Cliente: "+ vet[1]);
JOptionPane.showMessageDialog(null,"Endereço: "+ vet[2]);
JOptionPane.showMessageDialog(null,"Empresa: "+ vet[3]);
}
GOSTEI 0
Bruno Andrade
09/04/2009
Valeu pessoal pelas respostas, me ajudaram bastante!!!
GOSTEI 0