Panels & Layout Managers 28 Panels & Layout Managers
Previously Coursework Support
Overview Panels & Layout Manager Positioning Elements Some of the Layout Managers Using Layout Managers Layout Manager Sample
Positioning Elements Layout Managers determines the size and position of the components within a container Layout manager has the final say on the size and position of the components within the container A layout manager is an object that implements the LayoutManager interface Common containers of interest are JPanel and Content Panes
Some of the Layout Managers BorderLayout Places components in up to five areas: top, bottom, left, right, and centre BoxLayout Places components in a single row or column CardLayout Used to display just one element from a list of components at a time add(Component, int) add(Component) add(Component, String)
Some of the Layout Managers FlowLayout Places components in a single row, starting a new row if its container is not sufficiently wide. It is the default Layout Manager for JPanel GridBagLayout Places components within a grid of cells, allowing components to span more than one cell GridLayout Places components in a grid of cells where each cell is exactly the same size and each component takes all the available space within its cell add(Component) add(Component, GridBagConstraints) add(Component)
Some of the Layout Managers GroupLayout with the horizontal and vertical layouts separately SpringLayout allows to specify relationships between the edges of components under its control GroupLayout and SpringLayout were developed for use by GUI builder tools
Using Layout Managers Methods to use Create Layout Manager Set the Layout Manager in the Container setLayout() Add Components into the Container add(…)
Lets code with a BorderLayout! Layout Manager Sample Lets code with a BorderLayout!
Layout Manager Sample JPanel mainView = new JPanel(new BorderLayout()); JButton jb1 = new JButton("Button 1 (PAGE_START)"); JButton jb2 = new JButton("Button 2 (CENTER)"); JButton jb3 = new JButton("Button 3 (LINE_START)"); JButton jb4 = new JButton("Button 4 (PAGE_END)"); JButton jb5 = new JButton("5 (LINE_START)"); setContentPane(mainView); mainView.add(jb1, BorderLayout.PAGE_START); mainView.add(jb2, BorderLayout.CENTER); mainView.add(jb3, BorderLayout.LINE_START); mainView.add(jb4, BorderLayout.PAGE_END); mainView.add(jb5, BorderLayout.LINE_END);
References A Visual Guide to Layout Managers Using Layout Managers http://download.oracle.com/javase/tutorial/uiswing/layout/visual.html#card Using Layout Managers http://download.oracle.com/javase/tutorial/uiswing/layout/using.html