You can position components on a container by using absolute positioning, but this technique is painful and usually unnecessary. The better way to go is using a layout manager that handles positioning for you, based on simple rules. An excellent feature in Swing is having a default layout manager for every container. You can always replace the default with another one, but you don't have to. Every container, by default, has a layout manager. For example, BorderLayout is the default layout manager for every content pane. There are many more layout managers than just these, including DefaultMenuLayout, OverlayLayout, ScrollPaneLayout, SpringLayout, TextLayout, and ViewportLayout, but the following six layout managers are the ones I recommend you use for your solution.
The following code shows how you could lay out components left to right, in two rows and two columns: JButton firstComponent = new JButton; JButton secondComponent = new JButton; JButton thirdComponent = new JButton; JButton fourthComponent = new JButton; int rows = 2; int columns = 2; JPanel panel = new JPanel(new GridLayout(rows, columns)); panel.add(firstComponent); panel.add(secondComponent); panel.add(thirdComponent); panel.add(fourthComponent); |