I mean I have a frame with a button w/ action listener and 4 different frames. When I click the button it will randomly open one of those 4 frames. For example is I have frame 1,2,3,4. If I click my button it will randomly show one of those frames via setVisible(true) i've already set the code to make it visible and make the current frame invisible my only problem is that I don't know how the button will randomly pick from 4 frames
Asked
Active
Viewed 209 times
-1
-
`(int)(Math.round(Math.random() * 3))` should return a random value between 0-3. All you need from there is either an `array` containing each frame or a `switch` or `if` statement to implement the logic of showing the frame – MadProgrammer Mar 11 '13 at 23:46
-
1Don't use 4 child frames. Instead use JDialogs. An application should generally only have a single main frame. – camickr Mar 12 '13 at 01:10
-
See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556) – Andrew Thompson Mar 12 '13 at 11:01
-
possible duplicate of [Generating random number in a range with Java](http://stackoverflow.com/questions/363681/generating-random-number-in-a-range-with-java) – jball Jul 31 '13 at 21:28
1 Answers
1
Add all your frames into List or Array. Create Random object and generate random number between [0, 3]. Now, where you have list with frames and random number generator you are able to use it. For example:
frames.get(random.nextInt(frames.size()));
frames - List of all frames
random - instance of Random class.
See also:

Michał Ziober
- 37,175
- 18
- 99
- 146
-
-
Yes, it a good thought. But I prefer to use collection instead of switch statement. It more elegant for me. In the case when we want to add few new frames we can add it only to list and this all. Big switch is not readable for me. – Michał Ziober Mar 11 '13 at 23:56
-
Thanks guys for all your help, but this is too hard for me so I decided that i'll just make those four frames have their own button to show them and just put the buttons on the first frame – Russel Go Mar 12 '13 at 00:51