Botão que cria JLabel

8 respostas Resolvido
jamesw97

Estou a tempo tentando implementar um botão onde quando pressionado criará uma JLabel dentro de um painel, a principio o código é simples e está funcionando em outro programa que desenvolvi, mas por algum motivo o mesmo código não funciona nesse outro programa que estou implementando essa função.

Quando o úsuario clicar duas vezes em alguma JLabel criada ela mudará de cor

identar texto pré-formatado por 4 espaçospackage 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();
    lbAtividade = new javax.swing.JLabel();

    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 javax.swing.BoxLayout(pnAtividades, javax.swing.BoxLayout.LINE_AXIS));

    lbAtividade.setBackground(new java.awt.Color(255, 51, 51));
    lbAtividade.setText("AAA");
    lbAtividade.setOpaque(true);
    lbAtividade.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            lbAtividadeMouseClicked(evt);
        }
    });
    pnAtividades.add(lbAtividade);

    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, 62, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void btGerarActionPerformed(java.awt.event.ActionEvent evt) {                                        
    criarL();
    System.out.println("Clicou");
}                                       

private void lbAtividadeMouseClicked(java.awt.event.MouseEvent evt) {                                         
    if (evt.getClickCount() == 2 ) {
        lbAtividade.setBackground(Color.green);
        

    }
    
}                                        
public void criarL () {
    JLabel lbTarefa = new JLabel( );
    lbTarefa.setText("Disgraça");
    lbTarefa.setFont(new java.awt.Font("Tahoma", 0, 14));
    lbTarefa.setOpaque(false);
    
}
/**
 * @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.JScrollBar jScrollBar1;
private javax.swing.JLabel lbAtividade;
private javax.swing.JPanel pnAtividades;
// End of variables declaration

}

8 Respostas

jamesw97

Parte do código que importa:

public void criarL () {
    JLabel lbTarefa = new JLabel( );
    lbTarefa.setText("Disgraça");
    lbTarefa.setFont(new java.awt.Font("Tahoma", 0, 14));
    lbTarefa.setOpaque(false);
    
}
jamesw97
private void lbAtividadeMouseClicked(java.awt.event.MouseEvent evt) {                                         
    if (evt.getClickCount() == 2 ) {
        lbAtividade.setBackground(Color.green);
        

    }
    
}
jamesw97

Alguém? realmente preciso de uma força com isso :confused:

staroski

Você só está instanciando o JLabel, esqueceu de adicionar ele na sua tela.

jamesw97

Mesmo eu adicionando essas duas linhas no método criarL() não está funcionando.

lbTarefa.setVisible(true);
pnAtividades.add(lbTarefa);
staroski
Solucao aceita

Não precisa do setVisible(true).
Após o pnAtividades.add(lbTarefa) faça um pnAtividades.revalidate()

jamesw97

Obrigado @staroski de verdade, deu certinho aqui.

Agora se não for encomodar muito, como eu faria para que quando eu clicasse duas vezes em algum objeto lbTarefa apenas aquele ficasse verde?

Fiz aqui o seguinte, criei uma JLabel com o nome de lbTarefa e coloquei setVisible(false) porém com o código abaixo, para que (na minha cabeça funcionou :sweat_smile:) as jlabel criadas ao pressionar o botão meio que herdassem a funcionalidade MouseClicked, mas não deu muito certo, tem alguma idéia de como fazer isso?

private void lbAtividadeMouseClicked(java.awt.event.MouseEvent evt) {                                         
if (evt.getClickCount() == 2 ) {
    lbAtividade.setBackground(Color.green);
    

}

}

staroski

Adiciona um MouseListener àquele JLabel e trata o evento correspondente.

Criado 4 de agosto de 2019
Ultima resposta 6 de ago. de 2019
Respostas 8
Participantes 2