简体   繁体   English

如何使用GridLayout从JFrame获取组件?

[英]How to get components from a JFrame with a GridLayout?

I have a question about Java and JFrame in particular. 我有一个关于Java和JFrame的问题。 Let's say I have a JFrame that I am using with a GridLayout . 假设我有一个与GridLayout使用的JFrame Supposing that I have added JButton s in the JFrame , how can I gain access to the one I want using it's position (by position, I mean ax and ay, used to define the exact place on the Grid). 假设我在JFrame添加了JButton ,如何使用它的位置访问我想要的那个(按位置,我的意思是ax和ay,用于定义网格上的确切位置)。 I have tried several methods, for instance getComponentAt(int x, int y) , and have seen that those methods do not work as intended when combined with GridLayout , or at least don't work as intended in my case. 我已经尝试了几种方法,例如getComponentAt(int x, int y) ,并且看到这些方法在与GridLayout结合使用时不能按预期工作,或者至少在我的情况下不能按预期工作。 So I tried using getComponent() , which seems fine. 所以我尝试使用getComponent() ,这看起来很好。

The latest method, that seems to be on a right track for me is (assuming I have a JFrame with a GridLayout with 7 rows and 7 columns, x as columns, y as rows): 最新的方法,似乎对我来说是正确的轨道是(假设我有一个带有7行和7列的GridLayoutJFrame ,x作为列,y作为行):

public JButton getButtonByXAndY(int x, int y) {
    return (JButton) this.getContentPane().getComponent((y-1) * 7 + x);
}

image http://www.freeimagehosting.net/newuploads/9d6hq.jpg 图片http://www.freeimagehosting.net/newuploads/9d6hq.jpg

Using the above, say I want to get the JButton at (4, 4), meaning the 25th JButton in the JFrame , I would index through the first 21 buttons at first, and then add 4 more, finally accessing the JButton I want. 使用上面的说法,我想把JButton放在(4,4),意思是JFrame的第25个JButton,我会首先索引前21个按钮,然后再添加4个按钮,最后访问我想要的JButton。 Problem is this works like that in theory only. 问题是这在理论上只是如此。 Any ideas? 有任何想法吗?

PS sorry for linking to an external website, but stack overflow won't allow me to upload the image, because I do not have the required reputation. PS抱歉链接到外部网站,但堆栈溢出不允许我上传图像,因为我没有所需的声誉。

This example compares two approaches: 示例比较两种方法:

  1. Maintain a List<JButton> and calculate the index algebraically. 维护List<JButton>并以代数方式计算索引。

  2. Extend JButton and allow each button to maintain its own grid location. 扩展JButton并允许每个按钮维护自己的网格位置。

GridLayout start at 0,0 and JButton at (4,4 -position in GridLayout) meaning the 32th (4*7+4 not 3*7+4) JButton in the JFrame. GridLayout从0,0开始,JButton在(GridLayout中的4,4位)开始,意味着JFrame中的第32个(4 * 7 + 4而不是3 * 7 + 4)JButton。 Sorry if I misunderstood the questions :( 对不起,如果我误解了这些问题:(

You can try: 你可以试试:

   public static JButton getButtonByXAndY(int x, int y) {
        return (JButton) f.getContentPane().getComponent(y * 7 + x);
    }

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

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