Skip to content
Advertisement

How to detect which button was clicked – Java

Problem: below some code to make a frame filled with buttons. After the button is clicked, I would need to know the coordinates of the button clicked. The program will afterwards check the status of that specific tile and depending on the status it should change to a certain color. I’m having some issues when retracting this coordinate, could someone help me? (I’m only just learning how to program in Java, so my code might not be ideal)

Code:

JavaScript

Advertisement

Answer

If by coordinates you mean the actualx and y placement location of the button clicked upon then you can use this within your buttons ActionPerformed event:

JavaScript

Will print the top left location of the button clicked upon. This isn’t very helpful however since these locations can change if the Form is resized in any way.

If you mean by grid location as in the row and column of the button clicked upon then the easiest would be to ensure that an identifier is applied to each of the buttons by placing the grid location into the buttons Name property, when creating your buttons, for example:

JavaScript

Then in your buttons ActionPerformed event:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement