JTextField becomes huge in a HorizontalBox
07:44 20 May 2014

Please consider this Java code fragment:

Box buttonBox = Box.createHorizontalBox();
buttonBox.add(new JCheckBox("Select all"));
buttonBox.add(Box.createHorizontalGlue());
buttonBox.add(new JLabel("Filter: "));
buttonBox.add(new JTextField());

Box paneBox = Box.createVerticalBox();
paneBox.add(buttonBox);
paneBox.add(new JScrollPane(jList));

For some reason I don't get, the JTextField takes up most of the screen. The JList isn't even visible anymore. I would like to know why and how to fix it.

  1. When I comment the line with the JTextField, it looks fine (except no JTextField, of course). Why does the JCheckBox and the JLabel not get ridiculously big? What is the purpose of a one-line JTextField being able to take up almost the whole screen?

  2. Most people suggest to set the size of the JTextField field to my needs. However, I read that I should not call these methods, but let the LayoutManager take care of it. Now what is the most elegant solution to prevent the JTextField from becoming so big?

java swing layout-manager jtextfield