The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.
See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.
GroupLayout
layout manager combined with a builder tool to lay out your GUI. One such builder tool is the
NetBeans IDE. Otherwise, if you want to code by hand and do not want to use GroupLayout
, then GridBagLayout
is recommended as the next most flexible and powerful layout manager.
If you are interested in using JavaFX to create your GUI, see Working With Layouts in JavaFX.
Problem: How do I specify a component's exact size?
setSize
or setBounds
method on it. Otherwise, you need to provide size hints and then make sure you are using a layout manager that respects the size hints.getMinimumSize
, getPreferredSize
, and getMaximumSize
methods. What is nice about this approach is that each getXxxxSize
method can get the component's default size hints by invoking super.getXxxxSize()
. Then it can adjust the size, if necessary, before returning it. This is particularly handy for text components, where you might want to fix the width, but have the height determined from the content. However, sometimes problems can be encountered with GridBagLayout
and text fields, wherein if the size of the container is smaller than the preferred size, the minimum size gets used, which can cause text fields to shrink quite substantially.setMinimumSize
, setPreferredSize
, and setMaximumSize
methods.revalidate
method on it, to make sure that its containment hierarchy is laid out again. Then invoke the repaint
method.FlowLayout
and GridBagLayout
managers use the component's preferred size (the latter depending on the constraints that you set), but BorderLayout
and GridLayout
usually do not. The BoxLayout
manager generally uses a component's preferred size (although components can be larger), and is one of the few layout managers that respects the component's maximum size.
Problem: My component does not appear after I have added it to the container.
revalidate
and repaint
after adding a component before it will show up in your container.Problem: My custom component is being sized too small.
getPreferredSize
and getMinimumSize
methods? If so, do they return the right values?If you do not see your problem in this list, see Solving Common Component Problems.