I am currently designing GUI for an application using Swing. If you take a look at the picture, you see a yellow-colored JPanel, which is placed inside a BorderLayout. This panel uses a GridBagLayout to place components inside it. As you can see, one row of components consists of a label, a text field and a button. At the moment, there are two rows of components, vertically centered. I would like to them to be placed from top of the panel, though. I tried setting frame.setAlignmentY(TOP_ALIGNMENT) as well as gridBagConstraints.anchor property, but with no results. I think my approach to this problem is wrong, and instead of struggling for hours, I turn to good people of stackoverflow.
So the question is, how to force the grid of components to be vertically not centered, but on top? Thank you for any kind of advice pointing in me in the right direction.

EDIT (code):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
/**
*
* @author mt
*/
public class MainView extends JFrame {
public MainView() {
setPreferredSize(new Dimension(500, 500));
getContentPane().setLayout(new BorderLayout());
JPanel panel = new JPanel(new GridBagLayout());
panel.setBackground(Color.YELLOW);
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(4, 4, 4, 4);
c.gridx = 0;
c.gridy = 0;
panel.add(new JLabel("PokerStars"), c);
c.gridx = 1;
c.gridy = 0;
panel.add(new JTextField(20), c);
c.gridx = 2;
c.gridy = 0;
panel.add(new JButton("btn"), c);
c.gridx = 0;
c.gridy = 1;
panel.add(new JLabel("Full Tilt Poker"), c);
c.gridx = 1;
c.gridy = 1;
panel.add(new JTextField(20), c);
c.gridx = 2;
c.gridy = 1;
panel.add(new JButton("btn"), c);
add(panel, BorderLayout.LINE_START);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MainView();
}
});
}
}
OK, one way to solve your issue is to add an additional ‘invisible’ component at the end of your
paneland make it take all the extra available vertical space. Here is how you can do that:While this is not my favourite option, it will solve your issues in an acceptable manner. There is a probably a more interesting way to solve this but it requires to know what kind of UI you are targetting and how you expect the various component to behave when the window is resized.
In most cases, you should try not to set
gridx/gridyand use their default value (RELATIVE), it makes your code shorter and it is a lot easier to maintain if you have to insert one or more components.