Hola Que Tal Hola Que Tal - 1 year ago 63
Java Question

How can I select a random JButton from JFrame (Netbeans Interface)?

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.

Answer Source

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.