Java Swing Gridlayout:访问特定坐标

发布于 2024-12-20 05:06:37 字数 107 浏览 4 评论 0原文

我正在创建一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柠栀 2024-12-27 05:06:37

您不应该依赖 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 your GridLayout 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).

送君千里 2024-12-27 05:06:37

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 also GridBagLayout and Using Layout Managers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文