[RESOLVIDO] Java - mudar background de jlabel

Ó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);
    

}

Bom dia, pq nao ta funcionando? Dá erro? O que acontece? o código está correto.

Não sei se foi erro de formatação, mas faltou uma chave no final do if.

private void lbTarefaMouseClicked(java.awt.event.MouseEvent evt) {                                      
   if (evt.getClickCount() == 2 ) {
    lbTarefa.setBackground(Color.green);
   }
}
1 curtida

Você precisa adicionar um MouseListener para cada JLabel que for criado.

Exemplo:

public void criarL() {
    JLabel novoLabel = new JLabel();
    novoLabel.setText("Disgraça");
    novoLabel.setFont(new Font("Tahoma", 0, 14));
    novoLabel.setOpaque(true);
    novoLabel.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent evt) {
            lbTarefaMouseClicked(evt);
        }
    });
    pnAtividades.add(novoLabel);
    pnAtividades.revalidate();
}

private void lbTarefaMouseClicked(MouseEvent evt) {
    if (evt.getClickCount() == 2) {
        JLabel label = (JLabel) evt.getSource();
        label.setBackground(Color.GREEN);
    }
}
1 curtida

@rodriguesabner
O código simplesmente não funcionava, ele não apresentava nenhum erro de compilação entretanto não fazia o que deveria fazer. Mas com a resposta do staroski consegui implementar no código e deu certo, mesmo assim vlw amigo, de vdd :blush:

2 curtidas

Te agradeço novamente @staroski o código funcionou certinho aqui, mas confesso que não entendi muito bem essa linha que mencionei abaixo, comecei a pouco tempo a codar em java e estou engatinhando na orientação a objetos, mas confesso que nem mesmo nos livros que estou tomando como base vi algo parecido… é aquele ditado “time que está ganhando não se mexe” kkk mas gostaria de entender esse trecho para que caso no futuro eu possa dar manutenção no código ou implementar isso em alguma outra coisa sem problemas.

Se puder dar uma explicaçãozinha rápida dessa linha ou me direcionar para algum conteúdo que fale sobre ficarei grato xD

Todo evento AWT possui o método getSource() que retorna o objeto que disparou o evento.

Acontece que a assinatura do método retorna um Object e se você tiver uma variável do tipo Object você não vai conseguir chamar o método setBackground

Object label = evt.getSource();
label.setBackground(Color.GREEN); // erro de compilação, a classe Object não tem o método setBackground

Mas, você sabe que o objeto que disparou um evento é um objeto do tipo JLabel.
Como você sabe disso?
Oras, no método criarL() você criou um objeto do tipo JLabel e o MouseListener foi adicionado à este JLabel.

Então você faz um cast do retorno do método para o tipo JLabel, assim você tem uma variável do tipo JLabel e consegue “enxergar” o método setBackground.

O código abaixo:

JLabel label = (JLabel) evt.getSource();
label.setBackground(Color.GREEN);

Seria o equivalente a escrever isso:

Object objeto = evt.getSource();
JLabel label = (JLabel) objeto;
label.setBackground(Color.GREEN);