This section contains the detail about the layout managers in java Swing.
Working with layout managers
Java Swing Toolkit provides 2 types of components :
- Childrens
- Components
We use layout managers to arrange children into suitable groups or layouts. Layout managers are one of the most difficult parts of modern GUI programming. There might be situations, where we might not need a layout manager. We can use no layout manager, if we want, did not want to make the examples too complex. But to create truly portable, complex applications, we need layout managers.
Some of main layout managers are given below :
- FlowLayout manager
- CardLayout manager
- BorderLayout manager
- GridLayout manager
- BoxLayout manager
- GridBagLayout manager
- GroupLayout manager
- TableLayout manager
- ZoneLayout manager
- MigLayout manager
Complete list of layout managers with example are given in our example section next to the link of this tutorial's Link. Here, we only discuss about FlowLayout Manager :
FlowLayout Manager
The FlowLayout implements a simple layout style. Components are laid out from the upper-left corner, left to right and top to bottom. When no more components fit on a line , the next one appears on the next line. A small space is left between each component, above and below , as well as left and right. Here are the constructors for FlowLayout.
FlowLayout()
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
The first form creates the default layout , which centers components and leaves five pixels of space between each component. The second form lets you specify how each line is aligned.
The valid values for 'how'
are as follows :
- FlowLayout.LEFT
- FlowLayout.RIGHT
- FlowLayout.CENTER
- FlowLayout.LEADING
- FlowLayout.TRAILING
These values specify left, right, center, leading edge, and trailing
edge alignment respectively. The third constructor allows you to specify the
horizontal and vertical space left between components in horz
and vert
,
respectively.
Example :
package corejava; import java.awt.Dimension; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTree; public class FlowLayoutDemo extends JFrame { public FlowLayoutDemo() { setTitle("FlowLayout Example"); JPanel panel = new JPanel(); JTextArea area = new JTextArea("text area"); area.setPreferredSize(new Dimension(100, 100)); JButton button = new JButton("button"); panel.add(button); JTree tree = new JTree(); panel.add(tree); panel.add(area); add(panel); pack(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new FlowLayoutDemo(); } }
Output :
When you click on icon key of sub topics :
Note : Complete list of layout managers with example are given in our example section of main index page of java, next to the link of this tutorial's Link.
[ 0 ] Comments