First of all, I'm new to GUI so I may have made some terrible mistakes..

right, so I have a two dimensional array of buttons and I need to identify which button in the array is clicked, hovered over, and hovered off. For now I just want my program to say:

"*click* I am button" + x + y //when a button is pressed
"*hover over* I am button" + x + y //when the mouse enters a button
"*hover off* I am button" + x + y //when the mouse exits a button

So far I’ve solved the clicking with getActionCommand()

for (int i = 0; i < buttons.length; i++){
    for (int j = 0; j < buttons[0].length; j++) {
        buttons[i][j].setActionCommand(i + "_"  + j);
        buttons[i][j].addActionListener( new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("*click* I am button " + e.getActionCommand());

My real problem is the hovering because, as far as I know, the getActionCommand() isn't an option. I know of getComponent() however. This is my code so far:

buttons[i][j].addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseEntered(java.awt.event.MouseEvent evt) {
        //Print : "*hover over* I am button" + x + y
    public void mouseExited(java.awt.event.MouseEvent evt) {          
        //Print : "*hover off* I am button" + x + y 

My idea was to somehow save the x y coordinates of each button on the button object and then read it with getComponent().

I hope this wasn't too confusing.

Thanks in advanced.

Recommended Answers

All 2 Replies

identify which button in the array

In the listener you can call the Event class's getSource method to get a reference to the component causing the event.

To save information about a component/button (like where you put it in an array) you could use the JComponent's ClientProperties which is like a hashtable and has get and put methods.
Create an object to contain the info you want to associate with the button and put it in the ClientProperties table. When you later get a reference to the button, you can get the object that you put into the ClientProperites and extract the info you want from that object.

You could use an inner class for the listener that has the x,y coordinates as instance variables, that can be set by parameters in the constructor. When adding instances of this class to each button pass the appropriate values into the constructor.
Now there's no need for getSource or any of that stuff; just use the instance variables

buttons[i][j].addMouseListener(new myListener(i, j));

class myListener extends MouseAdapter {
   private final int x,y;
   public myListener(int x, int y) {
     this.x= x;
   public void mouseEntered(java.awt.event.MouseEvent evt) {
      System.out.println("*hover over* I am button " + x + ", " +y));
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.