Sou estudante de java, e estou com um problema de entendimento. Estudando o PADRÃO MVC, me deparei com o termo ouvinte, li e vi alguns tutoriais, daí partir para a prática só que agora enganchei. Criei um classe no NETBEANS OuvinteGUI e uma classe ouvinte OuvinteTeste. Quanto a construção tudo ocorreu bem, somente na hora de testar vi o problema, o BOTAO 2 não chama o evento no actionListener da classe ouvinte, poxa!! Gostaria de saber o porquê, se alguém puder me ajudar agradeço pela explicação.
seguem as duas classes:
CLASSE OuvinteTeste
package estudotablemodel.gui.ouvinte;
import estudotablemodel.gui.OuvinteGUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
/**
*
* @author User
*/
public class OuvinteTeste {
OuvinteGUI ouvinteGUI;
public OuvinteTeste(OuvinteGUI ouvinte) {
this.ouvinteGUI = ouvinte;
this.ouvinteGUI.bBotao2AddActionListener(new OuvinteOuvinteGUI());
}
class OuvinteOuvinteGUI implements ActionListener{
@Override
public void actionPerformed(ActionEvent evento) {
JOptionPane.showMessageDialog(null, "essa mensagem aparecerá!!???");
}
}
}
CLASSE OuvinteGUI
package estudotablemodel.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
/**
*
* @author User
*/
public class OuvinteGUI extends javax.swing.JFrame {
/**
* Creates new form OuvinteGUI
*/
public OuvinteGUI() {
initComponents();
bBotao.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evento){
JOptionPane.showMessageDialog(null, "essa mensagem aparecerá!!???");
}
});
}
public void bBotao2AddActionListener(ActionListener ouvinte) {
bBotao2.addActionListener(ouvinte);
}
/**
* 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() {
bBotao = new javax.swing.JButton();
bBotao2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
bBotao.setText("BOTAO");
bBotao.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bBotaoActionPerformed(evt);
}
});
bBotao2.setText("BOTAO 2");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(145, 145, 145)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(bBotao2)
.addComponent(bBotao))
.addContainerGap(178, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(142, Short.MAX_VALUE)
.addComponent(bBotao)
.addGap(18, 18, 18)
.addComponent(bBotao2)
.addGap(94, 94, 94))
);
pack();
}// </editor-fold>
private void bBotaoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<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(OuvinteGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OuvinteGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OuvinteGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OuvinteGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OuvinteGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton bBotao;
private javax.swing.JButton bBotao2;
// End of variables declaration
}
raghy, agradeço muito sua ajuda, mas o que realmente quero e separar a camada VISÃO (OuvinteGUI) da camada OUVINTE (OuvinteTeste). Gostaria que todas as ações ficassem no OuvinteTeste e na camada VISÃO (OuvinteGUI), ficasse só a parte visual. Mas não estou conseguindo fazer.
Usando uma dica declaração no construtor do raghy, consegui declarar minha classe da camada VISAO (OuvinteGUI), da classe da camada Ouvinte (OuvinteTeste). Seguem as classes remodeladas:
OuvinteGUI
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package estudotablemodel.gui;
import estudotablemodel.gui.ouvinte.OuvinteTeste;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
/**
*
* @author User
*/
public class OuvinteGUI extends javax.swing.JFrame {
/**
* Creates new form OuvinteGUI
*/
public OuvinteGUI() {
initComponents();
bBotao.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evento){
JOptionPane.showMessageDialog(null, "essa mensagem aparecerá!!???");
}
});
//Como vocês podem ver aqui está o pulo do gato.
OuvinteTeste ouv = new OuvinteTeste(this);
bBotao2.addActionListener(ouv);
}
/**
* 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() {
bBotao = new javax.swing.JButton();
bBotao2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
bBotao.setText("BOTAO");
bBotao.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bBotaoActionPerformed(evt);
}
});
bBotao2.setText("BOTAO 2");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(145, 145, 145)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(bBotao2)
.addComponent(bBotao))
.addContainerGap(178, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(142, Short.MAX_VALUE)
.addComponent(bBotao)
.addGap(18, 18, 18)
.addComponent(bBotao2)
.addGap(94, 94, 94))
);
pack();
}// </editor-fold>
private void bBotaoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<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(OuvinteGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OuvinteGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OuvinteGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OuvinteGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OuvinteGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton bBotao;
private javax.swing.JButton bBotao2;
// End of variables declaration
}
OuvinteTeste
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package estudotablemodel.gui.ouvinte;
import estudotablemodel.gui.OuvinteGUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
/**
*
* @author User
*/
public class OuvinteTeste implements ActionListener{
OuvinteGUI ouvinteGUI;
public OuvinteTeste(OuvinteGUI ouvinte) {
this.ouvinteGUI = ouvinte;
}
public void actionPerformed(ActionEvent evt){
// A variavel color precisa ter um valor inicial
// pois os if's poderiam todos falhar, em teoria.
JOptionPane.showMessageDialog(null, "FUNCIONOU QUE FOI UMA MARAVILHA!");
}
}