Search code examples
javaswinguser-interfacemouseeventjbutton

Drawing on a JButton[][] grid in a Java GUI


I have a 2D array of JButtons that I would like for the user to be able to draw lines on when the mouse is clicked. Grid of Buttons Image

Currently, when a user clicks on a specific JButton in the grid, it turns red. I want to be able to hold left-click down and hover over the JButtons I want to turn red. Here is what I have so far

      for (int i = 0; i < 40; i++) {
            for (int j = 0; j < 40; j++) {
                if (grid[i][j] != grid[0][0] && grid[i][j] != grid[39][39]) {

                    grid[i][j].addMouseListener(new java.awt.event.MouseAdapter(){

                        @Override
                        public void mousePressed(java.awt.event.MouseEvent evt) {
                            JButton button = (JButton) evt.getSource();
                            button.setBackground(Color.red);

                            paintedButtons.add(button);
                            button.transferFocus();
                            paintedButtons.add(button);
                        }

//                        public void mouseEntered(MouseEvent evt) {
//                                JButton button = (JButton) evt.getSource();
//                                button.setBackground(Color.red);
//
//                                paintedButtons.add(button);
//                            
//                        }
                    });
                }
                grid[0][0].setBackground(Color.GRAY);
                grid[39][39].setBackground(Color.GREEN);
            }
       }

The mouseEntered method almost does what I want. The problem is I only want it to happen when I hold down left-click. Thanks.


Solution

  • You can check if the left Mouse Button is pressed by using javax.swing.SwingUtilities in the mouseEntered event:

    @Override
    public void mouseEntered(MouseEvent evt) {
        if (SwingUtilities.isLeftMouseButton(evt))
            button.setBackground(Color.BLUE);
    }