javaswinguser-interfacesetbounds

Creating a GUI using setBounds()


I read that it is bad to use the setBounds() command for creating GUIs.

I know how to use Layout Managers and I have to say that they also have their disadvantages.

I'm programming a Game at the Moment and sometimes I need to stack Components above each other. I found no way to do this using Layout Managers, but setBounds() works perfectly.

Could you explain how I can stack Components using Layout Managers and also tell me why it is bad to use the setBounds() method for this purpose? Or is it fine, in conjunction with game GUIs coded in Java?


Solution

  • LayoutManagers take a lot of weight off your shoulders when it comes to stuff like calculating the correct size of a control, position everything in the right place when the GUI is resized etc.

    Basically you just tell the layout manager "I want this control over there in the corner" and the layout manager is responsible for keeping it there, whatever happens to the window, whether the user resizes it, moves it around,...

    A game interface is probably much more dynamically with elements constantly moving around. Layout managers usually are not particularly good at that stuff, they usually are designed for static user interfaces. Most desktop software (citation needed? ;) ) utilizes such static interfaces and layout managers are there to help the programmers of such interfaces so that they don't have to bother with all those details stated above.

    As a game interface is a use case thats not ideal for a layout manager, it is absolutely justifiable to not use it for everything. Still you probably could use a combination of both techniques - use a layout manager to position your static interface elements (you ought to have a menu button somewhere or something similar?) but use absolute positioning for all your dynamic elements that are moving around.

    Still, I'd recommend you looking into JavaFX, as stated in my comment above. It is much more better suited to draw animated, moving components and should save you a lot of work.

    Of course there are always exceptions - for example a Sudoku interface is something that you can do very well with layout managers, although it definitely is a game.