Get position/index of a JPanel in a GridLayout?
I'm trying to follow MVC-design and currently creating a MouseAdapter in my Controlle开发者_StackOverflow中文版r class. I have an array the same size as the GridLayout in one of my model classes. So when someone clicks a JPanel somewhere in the grid, I'd the MouseAdapter to notify the model and do something. The JPanels are in another class, View.
But for that I need the index/position of that particular JPanel, is there some way to get it?
I checked out the GetX and GetY methods of MouseEvent which state:
GetX - Returns the horizontal x position of the event relative to the source component.
Get Y - Returns the vertical y position of the event relative to the source component.
Relative to the source component, does that mean that the upper left corner of the JPanel is 0, 0? How then do I know which of the panels in the GridLayout was clicked?
You could build a Map in your view class and a create a method
public void getJPanelPos(JPanel panel)
to retrieve the position of the JPanel source of tyhe event
Put the information you require in the mouse listener that you add to the component. It's easier to do this in the set up than having mappings and look ups.
精彩评论