addMouseListener for a JPanel

75,464

Solution 1

JPanel doesn't have ActionListener capabilities. Instead, you need to use a MouseListener

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class CoordBoutons extends JFrame {

    CoordBoutons() {
        super("GridLayout");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Container contenant = getContentPane();
        contenant.setLayout(new GridLayout(8, 8));

        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                contenant.add(new CaseEchiquier(i, j));
            }
        }

        pack();
        setVisible(true);
    }

    class CaseEchiquier extends JPanel {

        private int lin, col;

        CaseEchiquier(int i, int j) {
            lin = i;
            col = j;
            setPreferredSize(new Dimension(80, 75));
            setBackground((i + j) % 2 == 0 ? Color.WHITE : Color.GRAY);
            addMouseListener(new MouseAdapter() {
                private Color background;

                @Override
                public void mousePressed(MouseEvent e) {
                    background = getBackground();
                    setBackground(Color.RED);
                    repaint();
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    setBackground(background);
                }
            });
//            addActionListener(new ActionListener() {
//                public void actionPerformed(ActionEvent evt) {
//                    System.out.println((char) ('a' + col) + "" + (8 - lin));
//
//                }
//            });
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame.setDefaultLookAndFeelDecorated(true);
                CoordBoutons coordBoutons = new CoordBoutons();
            }
        });
    }
}

Take a look at How to Write Mouse Listeners for more details...

Solution 2

The problem is that the method addActionListener does not exists for a JPanel. You should use the appropriate listener for this case (java.awt.event.MouseListener). Since MouseListener is an interface (and you don't want to implement all of its methods), you could use a MouseAdapter and override only the method(s) you need, like this:

addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        System.out.println((char)('a' + col) + "" + (8 - lin));
    }
});
Share:
75,464
user2360545
Author by

user2360545

Updated on August 03, 2022

Comments

  • user2360545
    user2360545 almost 2 years

    Today I have a problem.. My program make a 8x8 grid and show the coord when I click on a JButton.

    BUT I refuse to use JButton and I need to go for JPanel.. But my addMouseListener isn't working so I don't know how is it possible to fix that I'm searching since 4h.....

        package coordboutons;
    
        import java.awt.*;
        import java.awt.event.*;
        import javax.swing.*;
    
        public class CoordBoutons extends JFrame {
    
            CoordBoutons() {
                super("GridLayout");
                setDefaultCloseOperation(EXIT_ON_CLOSE);
                Container contenant = getContentPane();
                contenant.setLayout(new GridLayout(8, 8));
    
                for (int i = 0; i < 8; i++) 
                    for (int j = 0; j < 8; j++)
                        contenant.add(new CaseEchiquier(i, j));
    
                pack();
                setVisible(true);
            }
    
            **class CaseEchiquier extends JPanel** {
                private int lin, col;
                CaseEchiquier(int i, int j) {
                    lin = i;
                    col = j;
                    setPreferredSize(new Dimension(80, 75));
                    setBackground((i + j) % 2 == 0 ? Color.WHITE : Color.GRAY);
                    addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            System.out.println((char)('a' + col) + "" + (8 - lin));
    
                        }
                    });
                }
    
    
            }
    
            public static void main(String[] args) {
                JFrame.setDefaultLookAndFeelDecorated(true);
                CoordBoutons coordBoutons = new CoordBoutons();
            }
        }
    
    • MadProgrammer
      MadProgrammer almost 11 years
      I might be missing something here but ActionListener isn't a MouseListener
    • Reimeus
      Reimeus almost 11 years
      You mean addActionListener isnt working. That would be because you can't register JPanel with this type of listener
    • Anthony Raimondo
      Anthony Raimondo almost 11 years
      yours trying to add a mouselistener to your panels right? but your code sais actionListener, there is no actionlistener method in JPanel. and i think its a bad idea to have 64 newMouseListeners, you only need one for all 64 panels. so add a mouselistener as a parameter in your CaseEchiquier(int i, int j, MouseListener m)
    • wchargin
      wchargin almost 11 years
      "I refuse to use JButton" ... why?
  • user2360545
    user2360545 almost 11 years
    Oh men thank you so much I searched since long hours... And now I understood it works and I can get coords by clicking on a case =)
  • user2360545
    user2360545 almost 11 years
    Thank you so much I understood now =) Great help !
  • user2360545
    user2360545 almost 11 years
    Thank you for your help! Very useful ;) However, how can I get coordinates from each case without using "System.out.println". I want something like getX() and getY() with letters A-H (column) and numbers 1-8 (rows)
  • MadProgrammer
    MadProgrammer almost 10 years
    This will depend on more information then you actually have, you would need to know the width of each column and height of each row. A better solution might be to using the information from the class itself, the lin and col