Java Swing Gridlayout:访问特定坐标
我正在创建一个 Java swing GUI,并且已格式化 JPanel 以使用 GridLayout。我需要访问网格的特定“框”(即特定坐标),但我看不到这样做的方法。
我该怎么做?
I'm creating a Java swing GUI and I have formatted a JPanel to use a GridLayout. I need to access a specific "box" (i.e. specific coordinate) of the grid, but I cannot see a way to do so.
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不应该依赖 GUI 代码(视图)来为您提供有关程序数据(模型)的信息。最好的解决方案是从一开始就“知道”哪个组件在哪里——也许您应该有一个数据结构(二维数组?)来保存组件,并在网格中添加某些内容时进行更新。
不过,如果您想要快速且非常肮脏的修复,您可以开始玩游戏
JPanel.getComponentAt()
。不过,这需要像素坐标,因此您需要进行一些逆向工程来计算给定网格方块占用了多少空间。网格方块之间的间距 给出通过您的GridLayout
对象。但无论如何,不推荐这样做。我只是为了完整性而将其包括在内(因为这是对您的问题的更字面的回答)。You shouldn't depend on GUI code (the View) to give you information about program data (the model). The best solution would be to "know" which component is where from the start--maybe you should have a data structure (2D array?) that holds the components and is updated whenever something's added to the grid.
If you want a quick and very-dirty fix, though, you could start playing games with
JPanel.getComponentAt()
. This requires pixel coordinates, though, so you'd need to do some reverse-engineering to figure out how much space a given grid square takes up. The space between grid squares is given by yourGridLayout
object. This is not recommended whatsoever though. I'm just including it in the interest of completeness (and since it's a more literal response to your question).在
GridLayout
,“容器被分成大小相等的矩形。”您可以在想要显示为空的位置添加一个空的透明组件,例如new JLabel("")
。另请参阅GridBagLayout
和使用布局管理器。In
GridLayout
, "The container is divided into equal-sized rectangles." You can add an empty, transparent component in places you want to appear empty, e.g.new JLabel("")
. See alsoGridBagLayout
and Using Layout Managers.