How to get components from a JFrame with a GridLayout?
Posted
by
NlightNfotis
on Stack Overflow
See other posts from Stack Overflow
or by NlightNfotis
Published on 2012-05-31T10:07:09Z
Indexed on
2012/05/31
22:40 UTC
Read the original article
Hit count: 243
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 a x and a y, 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);
}
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?
P.S 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.
© Stack Overflow or respective owner