简体   繁体   中英

How to get components from a JFrame with a GridLayout?

I have a question about Java and JFrame in particular. Let's say I have a JFrame that I am using with a GridLayout . 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). 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. So I tried using getComponent() , which seems fine.

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):

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

image 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. 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.

This example compares two approaches:

  1. Maintain a List<JButton> and calculate the index algebraically.

  2. Extend JButton and allow each button to maintain its own grid location.

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. 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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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