Óla mestres,
tenho um código onde quando clico em um botão é criado uma JLabel cada vez que o botão é pressionado, porém preciso que quando o úsuario clicar 2 vezes em cima de alguma dessas JLabel criadas apenas aquelas fiquem com background verde… A ideia é a de uma lista onde cada JLabel representa uma tarefa, que ao clicar 2 vezes e ela ficar verde significa que aquela tarefa foi cumprida.
Pensei que criando uma JLabel lbTarefa e adicionando um mouseevent a ela todas as lbTarefas criadas ao clicar no botão possuissem as mesma ações desse mouseEvent porém, isso só funcionou na minha cabeça na teória não deu certo. Por favor se alguém puder dar uma força agradeço muito.
Método que cria as JLabel:
public void criarL () {
JLabel lbTarefa = new JLabel( );
lbTarefa.setText("Disgraça");
lbTarefa.setFont(new java.awt.Font("Tahoma", 0, 14));
lbTarefa.setOpaque(false);
lbTarefa.setVisible(true);
pnAtividades.add(lbTarefa);
pack();
}
Código completo:
package codigoTeste;
import java.awt.Color;
import javax.swing.JLabel;
public class T4 extends javax.swing.JFrame {
/**
* Creates new form T4
*/
public T4() {
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() {
jScrollBar1 = new javax.swing.JScrollBar();
btGerar = new javax.swing.JButton();
pnAtividades = new javax.swing.JPanel();
lbTarefa = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btGerar.setText("Gerar");
btGerar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btGerarActionPerformed(evt);
}
});
pnAtividades.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 255)));
pnAtividades.setLayout(new java.awt.BorderLayout());
lbTarefa.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
lbTarefa.setText("Exemplo teste");
lbTarefa.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lbTarefaMouseClicked(evt);
}
});
pnAtividades.add(lbTarefa, java.awt.BorderLayout.CENTER);
jButton1.setText("jButton1");
pnAtividades.add(jButton1, java.awt.BorderLayout.PAGE_START);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btGerar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(pnAtividades, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(pnAtividades, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btGerar)
.addGap(0, 8, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btGerarActionPerformed(java.awt.event.ActionEvent evt) {
criarL();
System.out.println("Clicou");
}
public void criarL () {
JLabel lbTarefa = new JLabel( );
lbTarefa.setText("Disgraça");
lbTarefa.setFont(new java.awt.Font("Tahoma", 0, 14));
lbTarefa.setOpaque(false);
lbTarefa.setVisible(true);
pnAtividades.add(lbTarefa);
pack();
}
private void lbTarefaMouseClicked(java.awt.event.MouseEvent evt) {
if (evt.getClickCount() == 2 ) {
lbTarefa.setBackground(Color.green);
}
}
/**
* @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(T4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(T4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(T4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(T4.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 T4().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btGerar;
private javax.swing.JButton jButton1;
private javax.swing.JScrollBar jScrollBar1;
private javax.swing.JLabel lbTarefa;
private javax.swing.JPanel pnAtividades;
// End of variables declaration
}
Minha idéia que achei que funcionaria mas não está funcionando
private void lbTarefaMouseClicked(java.awt.event.MouseEvent evt) {
if (evt.getClickCount() == 2 ) {
lbTarefa.setBackground(Color.green);
}