Olá estou tendo problemas para utilizar variaveis nos actionPerformed dos meus botões.
Estou criando varios botões dinamicamente e caso a referencia do botão já existe no banco ele preciso chamar um metodo diferente para alterar a ação ao inves de fazer uma nova…
Quando estou chamando o botão ele está sempre pegando a ultima ação ao inves de pegar a ação a ele referenciada
Meu maior problema seria:
//Adiciona o actionlistener do botão
botao.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
chamaAlterar(aco,etapa,equipa);
}
});
Nesta parte do codigo tenho “aco” que é o objeto ação,preciso que cada essa ação se torne estatica a partir do momento que ela foi inserida neste actionListener, pois o for irá sobreescrever esta ação com um novo valor para ser usado no proximo botão…
Codigo completo,está confuso:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import model.DAO.AcaoDAO;
import model.DAO.EtapaDAO;
import model.DAO.PreventivaDAO;
import model.TO.Acao;
import model.TO.Equipamento;
import model.TO.Etapa;
import model.TO.Funcionario;
import model.TO.Preventiva;
import preventivaapp.ConfigTela;
import preventivaapp.Mensagens;
import preventivaapp.SeccaoUsuario;
/**
*
* @author F8051921
*/
public class AcaoPreventiva extends javax.swing.JDialog {
/**
* Creates new form AcaoPreventiva
*/
Etapa etp = new Etapa();
EtapaDAO dao = new EtapaDAO();
Preventiva prv = new Preventiva();
PreventivaDAO prvdao = new PreventivaDAO();
SeccaoUsuario sec = new SeccaoUsuario();
Funcionario fun = new Funcionario();
AcaoDAO acaoDAO = new AcaoDAO();
Acao aco = new Acao();
Mensagens msg = new Mensagens();
public AcaoPreventiva(){
initComponents();
}
public AcaoPreventiva(java.awt.Frame parent, boolean modal,final Equipamento equipa) {
super(parent, modal);
initComponents();
//Seta o icone e deixa a tela no centro
new ConfigTela(this);
//Inicia os componentes
iniciaTela(equipa);
}
private void iniciaTela(final Equipamento equipa){
//Define o titulo da janela
this.setTitle("Preventiva "+ equipa.getNome());
//Alimenta a funcionario
fun.setEmail(sec.getEmail());
fun.setIdGestor(sec.getIdgestor());
fun.setMatricula(sec.getMatricula());
fun.setNome(sec.getNome());
fun.setSenha(sec.getSenha());
fun.setSuperuser(sec.getSuperuser());
fun.setTelefone(sec.getTelefone());
//Alimenta a preventiva
Date data = new Date(System.currentTimeMillis());
String date = data.toString();
date = date.substring(0,date.length()-3);
List<Preventiva> preventivas = prvdao.getListaWhere(sec.getIdfuncionario(), equipa.getIdequipamento(),date);
for(Preventiva preventiva : preventivas){
prv.setData(preventiva.getData());
prv.setConcluida(preventiva.getConcluida());
prv.setIdequipamento(equipa);
prv.setIdfuncionario(fun);
prv.setIdpreventiva(preventiva.getIdpreventiva());
prv.setIdEquipamento(preventiva.getIdEquipamento());
prv.setIdFuncionario(preventiva.getIdFuncionario());
}
//Seta o Layout como box para adicionar os botões um abaixo do outro
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
//Faz uma busca pelo TIPO do equipamento retornando as etapas dele
List<Etapa> etapas = dao.getListaWhereTipo(equipa.getTipo());
for(final Etapa etapa : etapas){
etp.setDescricao(etapa.getDescricao());
etp.setIdetapa(etapa.getIdetapa());
etp.setNome(etapa.getNome());
etp.setTipo(etapa.getTipo());
JButton botao;
botao = new JButton(etapa.getNome());
//Seta o tamanho do botão
Dimension dim = new Dimension();
dim.setSize(2060, 30);
botao.setMinimumSize(dim);
botao.setMaximumSize(dim);
//Carrega a ação para saber qual o Status(campo concluida) dela
List<Acao> acoes = acaoDAO.getListaWhere(etp.getIdetapa(), prv.getIdpreventiva());
for(final Acao acao : acoes){
aco.setConcluida(acao.getConcluida());
aco.setData(acao.getData());
aco.setIdacao(acao.getIdacao());
aco.setIdetapa(acao.getIdetapa());
aco.setIdpreventiva(prv);
aco.setLog(acao.getLog());
aco.setObs(acao.getObs());
aco.setTitulolog(acao.getTitulolog());
//Se concluida = 0 Denied.png(caso não tenha também) se = 1 Valid.png se =2 Warning_2.png
//Para 0,1 e 2 chama para Alterar do contrario para criar uma nova
if(aco.getConcluida() == 1){
botao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ico/Valid.png")));
//Adiciona o actionlistener do botão
botao.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
chamaAlterar(aco,etapa,equipa);
}
});
}
if(aco.getConcluida() == 2){
botao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ico/Warning_2.png")));
//Adiciona o actionlistener do botão
botao.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
chamaAlterar(aco,etapa,equipa);
}
});
}
}//Fim do for
if(botao.getIcon() == null){
botao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ico/Denided.png")));
//Adiciona o actionlistener do botão
botao.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
chamaAcao(prv,etapa,equipa);
}
});
}
//else{
// //Adiciona o actionlistener do botão
// botao.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent evt) {
// chamaAcao(prv,etapa,equipa);
// }
// });
//}
//Adiciona o botão no pane(Jpanel que está dentro do Scrollpane)
pane.add(botao);
scroll.getViewport().setView(pane);
}
}
private void chamaAcao(Preventiva preventiva,Etapa etapa,Equipamento equipamento){
//Chama outro JDialog passando esse o antecessor como owner pelo cast
new AcaoView((Frame)this.getOwner(),true,preventiva,etapa,equipamento).setVisible(true);
//Refresh na tela
//TODO dar o refresh após realizar a preventiva
pane.removeAll();
iniciaTela(equipamento);
}
private void chamaAlterar(Acao acao,Etapa etapa,Equipamento equipamento){
//Chama outro JDialog passando esse o antecessor como owner pelo cast
new AcaoView((Frame)this.getOwner(),true,acao,etapa).setVisible(true);
//Refresh na tela
//TODO dar o refresh após realizar a preventiva
pane.removeAll();
iniciaTela(equipamento);
}
/**
* 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() {
scroll = new javax.swing.JScrollPane();
pane = new javax.swing.JPanel();
cmbCompleta = new javax.swing.JComboBox();
lblPreventiva = new javax.swing.JLabel();
btnOk = new javax.swing.JButton();
btnCancel = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
javax.swing.GroupLayout paneLayout = new javax.swing.GroupLayout(pane);
pane.setLayout(paneLayout);
paneLayout.setHorizontalGroup(
paneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 595, Short.MAX_VALUE)
);
paneLayout.setVerticalGroup(
paneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 306, Short.MAX_VALUE)
);
scroll.setViewportView(pane);
cmbCompleta.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Não", "Sim" }));
lblPreventiva.setText("Preventiva completa?");
btnOk.setText("Ok");
btnOk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOkActionPerformed(evt);
}
});
btnCancel.setText("Cancelar");
btnCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(scroll)
.addGroup(layout.createSequentialGroup()
.addComponent(lblPreventiva)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cmbCompleta, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnOk)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnCancel)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(scroll)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmbCompleta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblPreventiva)
.addComponent(btnOk)
.addComponent(btnCancel))
.addContainerGap())
);
pack();
}// </editor-fold>
private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {
//Salvar a preventiva
if(cmbCompleta.getSelectedIndex()==0){
prv.setConcluida(false);
}else{
prv.setConcluida(true);
}
try{
prvdao.altera(prv);
}catch(Exception e){
msg.errorMsg("Erro: "+e);
}finally{
this.dispose();
}
}
private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {
//Fecha a janela
this.dispose();
}
/**
* @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(AcaoPreventiva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AcaoPreventiva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AcaoPreventiva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AcaoPreventiva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AcaoPreventiva().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnCancel;
private javax.swing.JButton btnOk;
private javax.swing.JComboBox cmbCompleta;
private javax.swing.JLabel lblPreventiva;
private javax.swing.JPanel pane;
private javax.swing.JScrollPane scroll;
// End of variables declaration
}
