Search code examples
javaswingjpanellayout-managergridbaglayout

Java Swing UI component layout


I am working on java swing and I am stuck with a UI layout

My current output is as below.

enter image description here

I want to modify it a lil and add 2 text inputs in between as shown in sample below. Please help on how to achieve the text inputs side by side.

enter image description here


Solution

  • First of all: You should really give your components more meaningful names than jComboBox2.

    Your example picture is not that easy to produce with GridBagLayout. You have to understand that the layout will create a n*m grid and you can put your components (like textfields, labels, comboboxes, etc.) freely anywhere inside that grid.

    For example your jLabel4 is at the position 0/3 in the grid and though i'm not actually sure what a gridwidth of -1 does i'm pretty sure it's still at 0/3. If gridwidth was for example 3, your jLabel4 would span from 0/3 to 2/3.

    So if you want to put something between those two rows, you'll need to put it at the right grid coordinates and give it the right width and height.

    BUT: Sadly, getting it exactly as in your picture requires you to use some tricks (for example increase the grid width of the upper and lower components or add another panel containing the new row components instead of the components themselves). Try to somehow make it work (even if it doesn't look exactly like your picture) without those tricks first as that might help you understand how GridBagLayout actually works. As soon as you really understand that, it should not be that difficult to recreate your picture.