I have created a matrix of JButtons in a JFrame using the GUI of NetBeans. I want to select them randomly, but I don't have any idea how to do it. Any idea will help. Thanks.
Asked
Active
Viewed 680 times
0
-
You'll need to have them referenced in some kind of `List`. Then, iterate over the list randomly. – ifly6 Aug 11 '16 at 13:04
1 Answers
0
Having the list of JButtons.
List<JButton> buttons;
Simply pick one random from it with the Random
instance.
Random rnd = new Random();
int i = rnd.nextInt(buttons.size());
JButton btn = buttons.get(i);
Works on the same logic like arrays.

Nikolas Charalambidis
- 40,893
- 16
- 117
- 183
-
Thank you for comment! But how can i introduce the List elements? When i try to introduce an element, it says "non-static variable jToggleButton101 cannot be referenced from a static context" Thanks again. greetings. – Hola Que Tal Aug 11 '16 at 15:34
-
Cannot tell more if I don't see the code. Generally, this is the solution for your error: http://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static – Nikolas Charalambidis Aug 11 '16 at 15:38