How do I add an event to an icon?

0

I wanted to make clicking on an icon possible to open a screen, perform any action and so on.

I wanted to put different formats, so I do not use a JButton . For by passing the image to him, he continued "rectangular". More, if there is any component that can take the form of an image or even do with the JButton, it is also valid.

Example click on a small circle:

packagepacote01;importjavax.swing.ImageIcon;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JPanel;publicclassNovoClassextendsJFrame{privateJPanelpainel=newJPanel();publicNovoClass(){setSize(200,150);ImageIconimage=newImageIcon(getClass().getResource("/imagens/icone.png"));   
        JLabel imagelabel = new JLabel(image); 

        painel.add(imagelabel);
        add(painel);   
        setVisible(true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);      
    }

    public static void main(String[] args) {
        NovoClass novo = new NovoClass();
    }
}
    
asked by anonymous 27.05.2017 / 05:10

1 answer

1

To add a listener to a jLabel you can use addMouseListener , passing as a parameter an implementation of MouseListener called MouseAdapter , overwriting only the mouseClicked method. p>

The following is the section responsible for this:

imagelabel.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        System.out.println("clicou no icone");
    }
});

The full code below

public class NovoClass extends JFrame {
    private JPanel painel = new JPanel();

    public NovoClass() {
        setSize(200, 150);
        ImageIcon image = new ImageIcon(getClass().getResource("/imagens/icone.png"));
        JLabel imagelabel = new JLabel(image);
        //Adiciona o mouse listener
        imagelabel.addMouseListener(getMouseListener());

        painel.add(imagelabel);
        add(painel);
        setVisible(true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    //Cria o mouse listener
    public MouseListener getMouseListener() {
        //Utiliza a implementação do mouseAdapter
        return new MouseAdapter() {
            //Faz a sobre-escrita apenas no click
            public void mouseClicked(MouseEvent e) {
                System.out.println("clicou no icone");
            }
        };
    }

    public static void main(String[] args) {
        NovoClass novo = new NovoClass();
    }
}
    
27.05.2017 / 07:36