I have a standalone JPanel which I then need to dock to my JFrame. I need the components of my JPanel to be centered but I can't find the way. I show pictures:
This is how it currently looks:
This is how I would like it to look:
The 2 centered buttons.
In that window, I have defined the JFrame on one side and the panel that shows all those buttons on the other, since the main panel is going to change.
My JPanel has a BorderLayout, in the South position I added the Exit button and in the Center is the GridBagLayout that I need to center its components. In principle I only need to center those 2 buttons.
My idea was to place empty JLabels (without text) with constraint at weightx = 0.5 and weighty=0.5 diagonally (as if they were the corners of a square, leaving the 2 buttons in between), in this way I managed to center the buttons but, it is useful when the distribution is symmetric.
My question is, is there a neater way to center things? Since mine hardly adapts to changes where the image is no longer as symmetrical as those 2 buttons. Maybe you don't need to use GridBagLayout and I don't know. Any recommendation?
You can apply the GridBagLayout layout to center one or more components.
Center a component
Related: Java GUI - How to center a single button
Center two or more components
Related: How do I center JButtons (Main menu) in a frame?