[RESOLVIDO]JButton - Mouse/Click

4 respostas
V

Olá galera!
Meu JButton é utilizado basicamente para gerar um imagem.
Eu gostaria de saber como fazer essa imagem mudar ao passar o mouse e uma mudança rápida de imagem ao clickar.

Ex:
1 - O usuário ao passar o mouse a imagem muda. Se o mouse sair a imagem volta ao normal.
2 - O usuário ao clickar a imagem muda (efeito de profundidade), depois do efeito de profundidade a imagem muda para uma de “clickada”.

Acho que deu pra entender. Não quero nada pronto, apenas me auxiliem como puderem, se possível. Valeu galera! :smiley:

4 Respostas

mauricioadl

Acho que sua dúvida é sobre java swing, se for vc precisa de algo assim:

JButton botao = new JButton();

		botao.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				System.out.println("esta com o mouse sobre o botao");
			}

			@Override
			public void mouseExited(MouseEvent e) {
				System.out.println("saiu com o mouse de cima do botao");
			}

			@Override
			public void mouseClicked(MouseEvent e) {
				System.out.println("clicou no botao");
			}
		});
V

É isso msm! Valeu!

diogomalvezzi

Ola, tudo bem!
Não consegui reproduzir o que foi passado e gostaria de saber se podem me ajudar.
Segue a tela

http://imgur.com/zT1yE1p

Código
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package view;

//import java.awt.event.MouseAdapter;
//import java.awt.event.MouseEvent;
//import javax.swing.JButton;
import javax.swing.JOptionPane;

/**
 *
 * @author Malvezzi
 */
public class jfLogin extends javax.swing.JFrame {

    /**
     * Creates new form jfLogin
     */
    public jfLogin() {
        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() {

        jlUsuario = new javax.swing.JLabel();
        jlSenha = new javax.swing.JLabel();
        jtUsuario = new javax.swing.JTextField();
        jpfSenha = new javax.swing.JPasswordField();
        jbAcessar = new javax.swing.JButton();
        jbSair = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Login");

        jlUsuario.setFont(new java.awt.Font("Segoe Print", 0, 18)); // NOI18N
        jlUsuario.setForeground(new java.awt.Color(204, 0, 51));
        jlUsuario.setText("Usuário");

        jlSenha.setFont(new java.awt.Font("MS Reference Sans Serif", 1, 14)); // NOI18N
        jlSenha.setForeground(new java.awt.Color(0, 51, 204));
        jlSenha.setText("Senha");

        jtUsuario.setBackground(new java.awt.Color(255, 204, 204));
        jtUsuario.setForeground(new java.awt.Color(0, 0, 204));

        jpfSenha.setBackground(new java.awt.Color(204, 204, 255));
        jpfSenha.setForeground(new java.awt.Color(204, 0, 51));

        jbAcessar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jbAcessar.setForeground(new java.awt.Color(0, 102, 51));
        jbAcessar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/7820_32x32.png"))); // NOI18N
        jbAcessar.setText("Acessar");
        jbAcessar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAcessarActionPerformed(evt);
            }
        });

        jbSair.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jbSair.setForeground(new java.awt.Color(255, 0, 0));
        jbSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/7831_32x32.png"))); // NOI18N
        jbSair.setText("Sair");
        jbSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbSairActionPerformed(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()
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jlUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(jlSenha, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jtUsuario)
                            .addComponent(jpfSenha, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jbAcessar)
                        .addGap(35, 35, 35)
                        .addComponent(jbSair, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(129, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(42, 42, 42)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlUsuario)
                    .addComponent(jtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jpfSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbAcessar, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbSair, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(41, 41, 41))
        );

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

    private void jbSairActionPerformed(java.awt.event.ActionEvent evt) {                                       
        
        System.exit(0);
    }                                      

    private void jbAcessarActionPerformed(java.awt.event.ActionEvent evt) {                                          
        JOptionPane.showMessageDialog(this, "Seja bem vindo !"+
                "\n" + jtUsuario.getText());
        new jfPrincipal().setVisible(true);
        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(jfLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(jfLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(jfLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(jfLogin.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 jfLogin().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jbAcessar;
    private javax.swing.JButton jbSair;
    private javax.swing.JLabel jlSenha;
    private javax.swing.JLabel jlUsuario;
    private javax.swing.JPasswordField jpfSenha;
    private javax.swing.JTextField jtUsuario;
    // End of variables declaration                   
}

Caso alguem possa me ajudar a implementar com base na resposta do camarada fico grato.
Até mais

mauricioadl

Eh so usar o codigo no seu botao.

diogomalvezzi:
Caso alguem possa me ajudar a implementar com base na resposta do camarada fico grato. Até mais
jbAcessar.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseEntered(MouseEvent e) {
				System.out.println("esta com o mouse sobre o botao");
			}

			@Override
			public void mouseExited(MouseEvent e) {
				System.out.println("saiu com o mouse de cima do botao");
			}

			@Override
			public void mouseClicked(MouseEvent e) {
				System.out.println("clicou no botao");
			}
		});
Criado 14 de agosto de 2013
Ultima resposta 27 de abr. de 2014
Respostas 4
Participantes 3