layout managers csci 201l jeffrey miller, ph.d. http :// www - scf. usc. edu /~ csci 201 usc csci...
TRANSCRIPT
Layout ManagersCSCI 201L
Jeffrey Miller, Ph.D.
HTTP://WWW-SCF.USC.EDU/~CSCI201
USC CSCI 201L
Outline
USC CSCI 201L 2/29
▪ Layout Managers▪ Custom Layout Managers▪ Program
Layout Managers Overview
▪ Instead of solely using hard-coded values for placing components in a container, Java has layout managers› Layout managers provide a level of abstraction so the user
interface behaves and looks the same on all systems
▪ Layout managers determine the location at which components will be placed
▪ To set a layout manager on a container, use the setLayout(LayoutManager) method
USC CSCI 201L 3/29Layout Managers
LayoutManager Classes
▪ java.awt.LayoutManager is an interface ▪ There are a number of classes that implement the LayoutManager
interface› BasicComboBoxUI.ComboBoxLayoutManager,
BasicInternalFrameTitlePane.TitlePaneLayout, BasicInternalFrameUI.InternalFrameLayout, BasicOptionPaneUI.ButtonAreaLayout, BasicScrollBarUI, BasicSplitPaneDivider.DividerLayout, BasicSplitPaneUI.BasicHorizontalLayoutManager, BasicSplitPaneUI.BasicVerticalLayoutManager, BasicTabbedPaneUI.TabbedPaneLayout, BorderLayout, BoxLayout, CardLayout, DefaultMenuLayout, FlowLayout, GridBagLayout, GridLayout, GroupLayout, JRootPane.RootLayout, JSpinner.DateEditor, JSpinner.DefaultEditor, JSpinner.ListEditor, JSpinner.NumberEditor, MetalComboBoxUI.MetalComboBoxLayoutManager, MetalScrollBarUI, MetalTabbedPaneUI.TabbedPaneLayout, OverlayLayout, ScrollPaneLayout, ScrollPaneLayout.UIResource, SpringLayout, SynthScrollBarUI, ViewportLayout
▪ We will cover a few of the layout managers in this lecture, though other layout managers are used for other applications
USC CSCI 201L 4/29Layout Managers
BorderLayout
▪ When you add a component, you can specify you want to add it to the BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.EAST, BorderLayout.WEST, or BorderLayout.CENTER› Components in the north and south will have their height
acknowledged but the width will be expanded to the width of the frame› Components in the east and west will have their width acknowledged
but the height will be expanded to the height of the frame› Components in the center will have their heights and widths expanded
to take up whatever space is remaining in the frame after the other four regions are rendered
▪ The default layout manager for a JFrame is BorderLayout
USC CSCI 201L 5/29Layout Managers
BorderLayout Example1 import java.awt.BorderLayout;2 import javax.swing.JButton;3 import javax.swing.JFrame;45 public class Test extends JFrame {6 public Test() {7 super("My Frame");8 setSize(300, 400);9 setLocation(200, 200);10 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);1112 JButton northButton = new JButton("North");13 add(northButton, BorderLayout.NORTH);14 JButton southButton = new JButton("South");15 add(southButton, BorderLayout.SOUTH);16 JButton eastButton = new JButton("East");17 add(eastButton, BorderLayout.EAST);18 JButton westButton = new JButton("West");19 add(westButton, BorderLayout.WEST);20 JButton centerButton = new JButton("Center");21 add(centerButton, BorderLayout.CENTER);2223 setVisible(true);24 }2526 public static void main(String [] args) {27 Test t = new Test();28 }29 }
USC CSCI 201L 6/29Layout Managers
FlowLayout
▪ When you add a component, the components will be added from left to right, top to bottom› Both the preferred height and width of each component
will be acknowledged
▪ If the components are bigger than the size of the container, they will still exist but will be displayed off the screen until the container is resized› Scrollbars do not automatically appear in containers but
they can be added
USC CSCI 201L 7/29Layout Managers
FlowLayout Example1 import java.awt.FlowLayout;2 import javax.swing.JButton;3 import javax.swing.JFrame;45 public class Test extends JFrame {6 public Test() {7 super("CSCI 201 Window");8 setSize(200, 220);9 setLocation(200, 200);10 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);1112 this.setLayout(new FlowLayout());1314 JButton button1 = new JButton("1");15 add(button1);16 JButton button2 = new JButton("2");17 add(button2);18 JButton button3 = new JButton("3");19 add(button3);20 JButton button4 = new JButton("4");21 add(button4);22 JButton button5 = new JButton("5");23 add(button5);2425 setVisible(true);26 }2728 public static void main(String [] args) {29 Test t = new Test();30 }31 }
USC CSCI 201L 8/29Layout Managers
CardLayout
▪ If multiple containers exist in the application but only one is to be displayed at a time, you could use CardLayout
▪ The programmer can choose which “card” is displayed › Think of this layout manager like a stack of playing cards
where all of the cards are there, but only one can be seen at a time
USC CSCI 201L 9/29Layout Managers
CardLayout Example1 import java.awt.CardLayout;2 import java.awt.event.ActionEvent;3 import java.awt.event.ActionListener;4 import javax.swing.JButton;5 import javax.swing.JFrame;6 import javax.swing.JPanel;78 public class Test extends JFrame {910 public Test() {11 super("CSCI 201 Window");12 setSize(200, 220);13 setLocation(200, 200);14 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);1516 JPanel outerPanel = new JPanel();17 outerPanel.setLayout(new CardLayout());1819 JPanel firstPanel = new JPanel();20 JButton button1 = new JButton("1");21 button1.addActionListener(new ButtonClicked("second", outerPanel));22 firstPanel.add(button1);2324 JPanel secondPanel = new JPanel();25 JButton button2 = new JButton("2");26 button2.addActionListener(new ButtonClicked("first", outerPanel));27 secondPanel.add(button2);2829 outerPanel.add(firstPanel, "first");30 outerPanel.add(secondPanel, "second");3132 add(outerPanel);33 setVisible(true);34 }
USC CSCI 201L 10/29Layout Managers
35 class ButtonClicked implements ActionListener {36 private String numberString;37 private JPanel jp;38 public ButtonClicked(String numberString, JPanel jp) {39 this.numberString = numberString;40 this.jp = jp;41 }42 public void actionPerformed(ActionEvent ae) {43 CardLayout cl = (CardLayout)jp.getLayout();44 cl.show(jp, numberString);45 }46 }4748 public static void main(String [] args) {49 Test t = new Test();50 }51 }
Whenbutton 1 is clicked
Whenbutton 2 is clicked
JTabbedPane
▪ JTabbedPane is not a layout manager, but it works similarly to the CardLayout
▪ Instead of having the other containers completely hidden, a JTabbedPane allows most of the container to be hidden except a small tab at the top› The tab can have text on it
USC CSCI 201L 11/29Layout Managers
JTabbedPane Example1 import javax.swing.JButton;2 import javax.swing.JFrame;3 import javax.swing.JPanel;4 import javax.swing.JTabbedPane;56 public class Test extends JFrame {78 public Test() {9 super("CSCI 201 Window");10 setSize(200, 220);11 setLocation(200, 200);12 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);1314 JTabbedPane tabbedPane = new JTabbedPane();1516 JPanel firstPanel = new JPanel();17 JButton button1 = new JButton("1");18 firstPanel.add(button1);1920 JPanel secondPanel = new JPanel();21 JButton button2 = new JButton("2");22 secondPanel.add(button2);2324 tabbedPane.add("First", firstPanel);25 tabbedPane.add("Second", secondPanel);2627 add(tabbedPane);28 setVisible(true);29 }3031 public static void main(String [] args) {32 Test t = new Test();33 }34 }
USC CSCI 201L 12/29Layout Managers
GridLayout
▪ GridLayout allows you to have your container emulate a grid, with columns and rows› The components are placed into each cell in the grid
▪ The GridLayout will take up the entire location in the container it occupies› Each cell will be the same size, which will possibly not
allow either the height or width to be acknowledged
USC CSCI 201L 13/29Layout Managers
GridLayout Example1 import java.awt.GridLayout;23 import javax.swing.JButton;4 import javax.swing.JFrame;5 import javax.swing.JPanel;67 public class Test extends JFrame {8 public Test() {9 super("CSCI 201 Window");10 setSize(200, 220);11 setLocation(200, 200);12 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);1314 JPanel jp = new JPanel();15 jp.setLayout(new GridLayout(3, 3));1617 for (int i=1; i < 10; i++) {18 JButton button = new JButton("" + i);19 jp.add(button);20 }2122 add(jp);23 setVisible(true);24 }2526 public static void main(String [] args) {27 Test t = new Test();28 }29 }
USC CSCI 201L 14/29Layout Managers
GridBagLayout
▪ The GridBagLayout is one of the most complex and flexible layout managers
▪ There is a grid of rows and columns, but the heights and widths do not have to be the same› Components can take up multiple cells as well
▪ GridBagLayout tries to acknowledge the preferred height and width of the components
▪ Each component gets added to the grid with a GridBagConstraints object to set the parameters for the component
▪ More information can be found at http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
USC CSCI 201L 15/29Layout Managers
GridBagContraints Object
▪ The GridBagConstraints object has the following properties› gridx, gridy
• Specify the row and column at the upper left corner of the component
› gridwidth, gridheight• Specify the number of rows or columns in the component’s display area
› fill• Used when the component’s display area is larger than the component’s preferred size• Values can be NONE, VERTICAL, HORIZONTAL, or BOTH
› ipadx, ipady• Specifies the internal padding of the component
› insets• Specifies the external padding of the component (through Insets object)
› anchor• Used when the component is smaller than its display area• Values an be CENTER (the default), PAGE_START, PAGE_END, LINE_START,
LINE_END, FIRST_LINE_START, FIRST_LINE_END, LAST_LINE_END, and LAST_LINE_START
› weightx, weighty• Weights are used to determine how to distribute space among columns and rows,
specified between 0.0 and 1.0 USC CSCI 201L 16/29Layout Managers
GridBagLayout Example1 import java.awt.GridBagConstraints;2 import java.awt.GridBagLayout;3 import javax.swing.JButton;4 import javax.swing.JFrame;5 import javax.swing.JPanel;67 public class Test extends JFrame {8 public Test() {9 super("CSCI 201 Window");10 setSize(200, 220);11 setLocation(200, 200);12 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);1314 JPanel jp = new JPanel();15 jp.setLayout(new GridBagLayout());1617 GridBagConstraints gbc = new GridBagConstraints();18 JButton button1 = new JButton("Button 1");19 gbc.gridx = 0;20 gbc.gridy = 0;21 jp.add(button1, gbc);2223 JButton button2 = new JButton("Button 2");24 gbc.gridx = 1;25 gbc.gridy = 0;26 gbc.ipadx = 50;27 jp.add(button2, gbc);2829 JButton button3 = new JButton("Button 3");30 gbc.gridx = 0;31 gbc.gridy = 1;32 gbc.gridwidth = 2;33 gbc.ipadx = 0;34 gbc.ipady = 40;35 jp.add(button3, gbc);3637 add(jp);38 setVisible(true);39 }
USC CSCI 201L 17/29Layout Managers
40 public static void main(String [] args) {41 Test t = new Test();42 }43 }
BoxLayout
▪ BoxLayout either stacks all of the components on top of each other or puts them next to each other› It works similarly to FlowLayout but with more functionality
▪ BoxLayout tries to acknowledge the preferred height and width of the components› If no preferred height or width is set, the component can
expand based on the arrangement of components
▪ Rigid area can be specified to allow a fixed-space between components
▪ Glue can be used to specify where excess space in a layout should go› Stretches and compresses based on the size of the container
USC CSCI 201L 18/29Layout Managers
BoxLayout Example1 import javax.swing.BoxLayout;2 import javax.swing.JButton;3 import javax.swing.JFrame;4 import javax.swing.JPanel;56 public class Test extends JFrame {7 public Test() {8 super("CSCI 201 Window");9 setSize(200, 220);10 setLocation(200, 200);11 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);1213 JPanel jp = new JPanel();14 jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));1516 JButton button1 = new JButton("Button 1");17 jp.add(button1);18 jp.add(Box.createGlue());19 JButton button2 = new JButton("Button 2");20 jp.add(button2);21 JButton button3 = new JButton("Button 3");22 jp.add(button3);2324 add(jp);25 setVisible(true);26 }2728 public static void main(String [] args) {29 Test t = new Test();30 }31 }
USC CSCI 201L 19/29Layout Managers
GroupLayout
▪ GroupLayout separates out formatting the horizontal layer from the vertical layer
▪ If we are trying to create the following GUI
› The horizontal group will be
› And the vertical group will be
USC CSCI 201L 20/29Layout Managers
GroupLayout
▪ The horizontal and vertical groups actually overlap› GroupLayout will not allow a component to only be added
to one group though – they must be added to both the vertical and horizontal group
▪ Components or groups can be added to other groups so we are not limited by only one component in each group
▪ GroupLayout is a fairly complex layout manager, but it is also very flexible
USC CSCI 201L 21/29Layout Managers
GroupLayout Example
USC CSCI 201L 22/29Layout Managers
45 ParallelGroup buttonGroup = layout.createParallelGroup();46 buttonGroup.addComponent(findButton);47 buttonGroup.addComponent(cancelButton);48 horizontal.addGroup(buttonGroup);49 layout.setHorizontalGroup(horizontal);5051 SequentialGroup vertical = layout.createSequentialGroup();52 ParallelGroup topRow = layout.createParallelGroup();53 topRow.addComponent(label);54 topRow.addComponent(textField);55 topRow.addComponent(findButton);56 vertical.addGroup(topRow);57 58 ParallelGroup bottomRow = layout.createParallelGroup();59 SequentialGroup buttonGroup1 = layout.createSequentialGroup();60 ParallelGroup firstButtonGroup = layout.createParallelGroup();61 firstButtonGroup.addComponent(caseCheckBox);62 firstButtonGroup.addComponent(wrapCheckBox);63 buttonGroup1.addGroup(firstButtonGroup);64 ParallelGroup secondButtonGroup = layout.createParallelGroup();65 secondButtonGroup.addComponent(wholeCheckBox);66 secondButtonGroup.addComponent(backCheckBox);67 buttonGroup1.addGroup(secondButtonGroup);68 bottomRow.addGroup(buttonGroup1);69 bottomRow.addComponent(cancelButton); 70 vertical.addGroup(bottomRow);71 72 layout.setVerticalGroup(vertical);7374 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);75 setVisible(true);76 }77 78 public static void main(String args[]) {79 Test t = new Test();80 }81 }
1 import javax.swing.GroupLayout;2 import javax.swing.GroupLayout.ParallelGroup;3 import javax.swing.GroupLayout.SequentialGroup;4 import javax.swing.JButton;5 import javax.swing.JCheckBox;6 import javax.swing.JFrame;7 import javax.swing.JLabel;8 import javax.swing.JTextField;910 public class Test extends JFrame {11 public Test() {12 super("Find");13 setSize(500, 130);14 setLocation(300, 300);15 JLabel label = new JLabel("Find What:");;16 JTextField textField = new JTextField();17 JCheckBox caseCheckBox = new JCheckBox("Match Case");18 JCheckBox wrapCheckBox = new JCheckBox("Wrap Around");19 JCheckBox wholeCheckBox = new JCheckBox("Whole Words");20 JCheckBox backCheckBox = new JCheckBox("Search Backwards");21 JButton findButton = new JButton("Find");22 JButton cancelButton = new JButton("Cancel");23 24 GroupLayout layout = new GroupLayout(getContentPane());25 getContentPane().setLayout(layout);26 layout.setAutoCreateGaps(true);27 layout.setAutoCreateContainerGaps(true);28 29 SequentialGroup horizontal = layout.createSequentialGroup();30 horizontal.addComponent(label);31 32 ParallelGroup searchBoxGroup = layout.createParallelGroup();33 searchBoxGroup.addComponent(textField);34 horizontal.addGroup(searchBoxGroup);35 36 SequentialGroup checkBoxGroup = layout.createSequentialGroup();37 ParallelGroup firstCheckbox = layout.createParallelGroup();38 firstCheckbox.addComponent(caseCheckBox);39 firstCheckbox.addComponent(wholeCheckBox);40 ParallelGroup secondCheckbox = layout.createParallelGroup();41 secondCheckbox.addComponent(wrapCheckBox);42 secondCheckbox.addComponent(backCheckBox);43 checkBoxGroup.addGroup(firstCheckbox);44 checkBoxGroup.addGroup(secondCheckbox);45 searchBoxGroup.addGroup(checkBoxGroup);
null Layout
▪ If you set the layout manager to null, you are able to place components in the container with absolute positioning
▪ If the container is resized, your components may not still appear in the same location (or may not be seen)› You are able to restrict a container from being resized
▪ You may want to set the bounds and size on your components so they appear how you want
USC CSCI 201L 23/29Layout Managers
null Layout Example1 import java.awt.Dimension;2 import javax.swing.JButton;3 import javax.swing.JFrame;4 import javax.swing.JPanel;5 6 public class Test extends JFrame {7 public Test() {8 super("CSCI 201 Window");9 setSize(300, 200);10 setLocation(300, 300);11 12 JPanel jp = new JPanel();13 jp.setLayout(null);14 15 JButton button1 = new JButton("One");16 Dimension button1Dimensions = button1.getPreferredSize();17 button1.setBounds(25, 25, button1Dimensions.width, button1Dimensions.height);18 jp.add(button1);19 20 JButton button2 = new JButton("Two");21 Dimension button2Dimensions = button2.getPreferredSize();22 button2.setBounds(75, 75, button2Dimensions.width, button2Dimensions.height);23 jp.add(button2);24 25 JButton button3 = new JButton("Three");26 Dimension button3Dimensions = button3.getPreferredSize();27 button3.setBounds(125, 125, button3Dimensions.width, button3Dimensions.height);28 jp.add(button3);29 30 add(jp);31 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);32 setVisible(true);33 }34 35 public static void main(String args[]) {36 Test t = new Test();37 }38 }
USC CSCI 201L 24/29Layout Managers
Outline
USC CSCI 201L 25/29
▪ Layout Managers▪ Custom Layout Managers▪ Program
Custom Layout Manager
▪ To create your own layout manager, create a class that implements the LayoutManager interface
▪ You will need to implement the following methods› void addLayoutComponent(String, Component) Called by the Container class's add methods.
Layout managers that do not associate strings with their components generally do nothing in this method.
› void removeLayoutComponent(Component) Called by the Container methods remove and removeAll. Layout managers override this method to clear an internal state they may have associated with the Component.
› Dimension preferredLayoutSize(Container) Called by the Container class's getPreferredSize method, which is itself called under a variety of circumstances. This method should calculate and return the ideal size of the container, assuming that the components it contains will be at or above their preferred sizes. This method must take into account the container's internal borders, which are returned by the getInsets method.
› Dimension minimumLayoutSize(Container) Called by the Container getMinimumSize method, which is itself called under a variety of circumstances. This method should calculate and return the minimum size of the container, assuming that the components it contains will be at or above their minimum sizes. This method must take into account the container's internal borders, which are returned by the getInsets method.
› void layoutContainer(Container) Called to position and size each of the components in the container. A layout manager's layoutContainer method does not actually draw components. It simply invokes one or more of each component's setSize, setLocation, and setBounds methods to set the component's size and position.
USC CSCI 201L 26/29Custom Layout Managers
Outline
USC CSCI 201L 27/29
▪ Layout Managers▪ Custom Layout Managers▪ Program
Programs
▪ Write a program that produces the GUI below with each tab displaying a different layout manager.
USC CSCI 201L 28/29Program
Programs
▪ Write a program that produces the GUI below without using GroupLayout.
▪ Write a program that produces the GUI below.
USC CSCI 201L 29/29Program