0

I have a 2 dimensional array of JButtons, and I would like to be able to have the button that my mouse is over to perform an action, such as change color. How can I do this? Thanks.

Here is how I am creating the buttons:

for(int r = 0;r<10;r++){
        for(int c = 0;c<10;c++){
            buttonArray[r][c] = new JButton();
        }
    }
2
  • You can create listener for each button and inside the listener add the specific work you want to perform. See this example JButton Background Color On Mouse Over. Commented Oct 13, 2016 at 13:25
  • Thank you! This helped a lot Commented Oct 13, 2016 at 13:29

1 Answer 1

1

Here is an example using a loop and a MouseAdapter (since you don't need all the methods from MouseListener ) :

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class JButtonHighlighter extends JPanel {

    public static void main(final String[] args) {

        JFrame frame = new JFrame();

        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new GridLayout(10, 10));

        JButton[][] buttonArray = new JButton[10][10];

        for (int r = 0; r < 10; r++) {
            for (int c = 0; c < 10; c++) {

                final JButton newButton = new JButton();

                final Color originalColor = newButton.getBackground();
                final Color highlightColor = Color.GREEN;

                newButton.addMouseListener(new MouseAdapter() {

                    @Override
                    public void mouseEntered(final MouseEvent e) {
                        newButton.setBackground(highlightColor);

                    }

                    @Override
                    public void mouseExited(final MouseEvent e) {
                        newButton.setBackground(originalColor);

                    }

                });

                buttonArray[r][c] = newButton;

                contentPanel.add(newButton);
            }
        }

        frame.setContentPane(contentPanel);
        frame.setSize(100, 100);
        frame.setVisible(true);

    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.