In order for the inscription to always remain above the text field, you need to change the layout of the internal panels. By default, there is FlowLayout , which lays out components in a line, and transfers them to a new line only if they do not fit. You can take BoxLayout or BorderLayout :
JPanel panel = new JPanel(); panel.setLayout( new BoxLayout( panel, BoxLayout.Y_AXIS ) ); JLabel lbl = new JLabel("Label "+row, SwingConstants.LEFT); JTextField jtf = new JTextField(); lbl.setAlignmentX( 0.5f ); // метка будет отцентрована panel.add(lbl); jtf.setPreferredSize(new Dimension(170, 25)); panel.add(jtf); panel.setPreferredSize(new Dimension(170, 51)); panel.setBorder(BorderFactory.createLineBorder(Color.red, 1));
To remove indents between lines, you need to decide what to do with them. If you need to stretch the lines vertically, then the constraints should have the same vertical weight for all the rows and stretching along both axes:
constraints.weighty = 1.0; constraints.fill = GridBagConstraints.BOTH;
In this case, the text field will begin to stretch, to avoid this, you can set a maximum size for it: jtf.setMaximumSize(new Dimension(Short.MAX_VALUE, 25));
If you need to collect the lines at the top of the form, you can remove the vertical weight, leave the stretch width, and after all the cycles insert an invisible empty component with a non-zero vertical weight. This component will occupy all free space.
for(int row = 0; row < 5; row++) { for(int col = 0; col < 5; col++) { /* ... */ jPanel4.add(panel, constraints); } } constraints.gridy = 100500; constraints.weighty = 100500f; jPanel4.add( new JPanel(), constraints );
Full code:
GridBagConstraints constraints = new GridBagConstraints(); constraints.weightx = 1.0; constraints.weighty = 0.0; constraints.anchor = GridBagConstraints.FIRST_LINE_START; constraints.ipadx = 3; constraints.ipady = 3; constraints.insets = new Insets(3, 3, 3, 3); constraints.fill = GridBagConstraints.BOTH; for(int row = 0; row < 5; row++) { for(int col = 0; col < 5; col++) { JPanel panel = new JPanel(); // BoxLayout с вертикальным расположением panel.setLayout( new BoxLayout( panel, BoxLayout.PAGE_AXIS ) ); JLabel lbl = new JLabel("Label "+row, SwingConstants.LEADING ); // выравнивание компонента зависит не только от его собственного // alignmentX, но и от alignmentX других компонентов // поэтому надо задавать и для textfield тоже lbl.setAlignmentX( Component.LEFT_ALIGNMENT ); panel.add(lbl); JTextField jtf = new JTextField(); jtf.setPreferredSize(new Dimension(170, 25)); // BoxLayout учитывает MaximumSize, если не указать // то textfield растянется в высоту jtf.setMaximumSize(new Dimension(Integer.MAX_VALUE, 25)); jtf.setAlignmentX( Component.LEFT_ALIGNMENT ); panel.add(jtf); panel.setBorder(BorderFactory.createLineBorder(Color.red, 1)); constraints.gridx = GridBagConstraints.RELATIVE; constraints.gridy = row; jPanel4.add(panel, constraints); } } // заполняем последний ряд GridBagLayout, нужно убрать отступы, // что бы не было заметно при минимальной высоте панели constraints.gridy = 100500; constraints.weighty = 100500f; constraints.ipadx = 0; constraints.ipady = 0; constraints.insets = new Insets( 0, 0, 0, 0 ); constraints.fill = GridBagConstraints.NONE; // Box.createVerticalStrut(0) создает невидимый компонент нулевой высоты jPanel4.add( Box.createVerticalStrut( 0 ), constraints );