简体   繁体   English

获取GridLayout中JPanel的位置/索引?

[英]Get position/index of a JPanel in a GridLayout?

I'm trying to follow MVC-design and currently creating a MouseAdapter in my Controller class. 我正在尝试遵循MVC设计,当前在我的Controller类中创建一个MouseAdapter。 I have an array the same size as the GridLayout in one of my model classes. 我的一个模型类中的数组大小与GridLayout相同。 So when someone clicks a JPanel somewhere in the grid, I'd the MouseAdapter to notify the model and do something. 因此,当有人单击网格中某个位置的JPanel时,我会让MouseAdapter通知模型并执行某些操作。 The JPanels are in another class, View. JPanels在另一个类View中。

But for that I need the index/position of that particular JPanel, is there some way to get it? 但是为此,我需要特定JPanel的索引/位置,是否有某种方法可以获取它?

I checked out the GetX and GetY methods of MouseEvent which state: 我签出了MouseEvent的GetX和GetY方法,它们指出:

GetX - Returns the horizontal x position of the event relative to the source component. GetX-返回事件相对于源组件的水平x位置。

Get Y - Returns the vertical y position of the event relative to the source component. 获取Y-返回事件相对于源组件的垂直y位置。

Relative to the source component, does that mean that the upper left corner of the JPanel is 0, 0? 相对于源组件,这是否意味着JPanel的左上角是0、0? How then do I know which of the panels in the GridLayout was clicked? 那么我怎么知道GridLayout中的哪个面板被单击了?

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. 在设置中执行此操作比进行映射和查找要容易。

You could build a Map in your view class and a create a method 您可以在视图类中构建Map并创建方法

public void getJPanelPos(JPanel panel) 

to retrieve the position of the JPanel source of tyhe event 检索tyhe事件的JPanel源的位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM