How to properly use the MouseMotionListener to press JButtons?

依然范特西╮ 提交于 2019-12-05 15:24:48

I think the problem you're having is that you're trying to use JButton for something it's not designed to do. I would go with a much simpler control, like JLabel, so that you won't have all the extra functionality that JButton has.

Secondly, your litSquares array is clearly a Data Clump. You absolutely should be creating your own custom control (which can either extend JComponent or extend JLabel), depending on whether JLabel meets your needs, that contains the other information that should be paired with the control itself.

Thirdly, you might not want the state of the button to be a boolean, you probably want it to be an enum... like

public enum State {
    UNLIT, LIT, CURRENTLY_SELECTED;
}

so that you can see which components are being newly color-flipped.

Finally, as was mentioned in the comments, use public Component getComponentAt(int x, int y) to be able to figure out what the MouseMotionListener was dragged over, and use that to change the color.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!