unit 121 a layout manager is an object that determines the manner in which components are arranged...

27
Unit 12 1 •A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of the two interfaces: LayoutManger or LayoutManger2. There are several predefined layout managers defined in the Java standard class library: Defined in the AWT Defined in Swing Flow Layout Border Layout Card Layout Grid Layout GridBag Layout Box Layout Overlay Layout Introduction to GUI Layout Managers

Upload: melvin-beatley

Post on 31-Mar-2015

230 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 1

• A layout manager is an object that determines the manner in which components are arranged in a container.

• Each layout manager implements one of the two interfaces:

LayoutManger or LayoutManger2.

• There are several predefined layout managers defined in the Java standard class library:

Defined in the AWT

Defined in Swing

Flow LayoutBorder LayoutCard LayoutGrid LayoutGridBag LayoutBox Layout

Overlay Layout

Introduction to GUI Layout Managers

Page 2: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 2

• Every container has a default layout manager, but we can explicitly set the layout manager as well.

• Each layout manager has its own particular rules governing how the components will be arranged.

• Some layout managers pay attention to a component's preferred size or alignment, while others do not.

• A layout manager attempts to adjust the layout as components are added and as containers are resized.

• We can use the setLayout method of a container to change its layout manager.

JPanel panel = new JPanel();panel.setLayout (new BorderLayout());

Layout Managers

Page 3: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 3

Introduction to Flow Layout

• FlowLayout places components sequentially on a row from left to right in the order added and then moves to the next row.

• Rows are created as needed to accommodate all of the components.• Components placement depends on the current size of the container.• When the container is resized the components are automatically resized.• FlowLayout is the default layout for panels.

• Each row of components is centered horizontally in the window by default, but could also be aligned left or right

• The horizontal and vertical gaps between the components can be explicitly set also

• FlowLayout has three constructors:o FlowLayout()o FlowLayout(int align): The alignment argument can be FlowLayout.LEADING,

FlowLayout.CENTER, or FlowLayout.TRAILING. o LEADING specifies that the components be left-aligned and TRAILING specifies right

alignment. o FlowLayout(int align, int hgap, int vgap)

Page 4: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 4

Example 1: Flow Layout Test

1 import javax.swing.*; 2 class TestFlowLayout extends JFrame{ 3 JPanel panel = new JPanel(); 4 public TestFlowLayout(){

Note: we did not set the layout because Flow Layout is the default one for the panel

5 panel.add(new JButton("1")); 6 panel.add(new JButton("2")); 7 panel.add(new JButton("3")); 8 panel.add(new JButton("4")); 9 panel.add(new JButton("5"));10 panel.add(new JButton("6"));11 panel.add(new JButton("7"));12 setContentPane(panel);13 setSize(300,300);14 setTitle("Flow Layout Test");15 setVisible(true); }

17 public static void main(String [] args){18 new TestFlowLayout();19 } }

Page 5: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 5

Introduction to Grid Layout

• A grid layout presents a container’s components in a rectangular grid of rows and columns.

• One component is placed in each cell of the grid, and all cells have the same size.

• As components are added to the container, they fill the grid from left-to-right and top-to-bottom (by default).

• The size of each cell is determined by the overall size of the container.

• GridLayout has three constructors:

o GridLayout()

o GridLayout(int rows, int cols)

o GridLayout(int rows, int cols, int hgap, int vgap)

Page 6: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 6

Example 2: Grid Layout Test

1 import java.awt.*; import javax.swing.*; 2 import javax.swing.border.*; 3 class TestGridLayout extends TestFlowLayout{ 4 public TestGridLayout(){ 5 panel.add(new JButton("8")); 6 panel.add(new JButton("9")); 7 panel.add(new JButton("*")); 8 panel.add(new JButton("0")); 9 panel.add(new JButton("#"));10 JLabel jlb = new JLabel(“ICS 201", SwingConstants.CENTER);11 Border b

=BorderFactory.createBevelBorder(BevelBorder.RAISED);12 jlb.setBorder(BorderFactory.createTitledBorder(b,“Section 02"));13 panel.add(jlb);14 setTitle("Grid Layout Test");15 panel.setLayout(new GridLayout(0,3));16 setVisible(true);17 }18 public static void main(String [] args){19 new TestGridLayout();20 }21 }

GridLayout class to create an instance that has three columns and as many rows as necessary

Page 7: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 7

Introduction to Border Layout

• BorderLayout places components according to five areas: "North", "South",

"East", "West" and "Center".

• When you enlarge a container the center area grabs as much of the new space

as possible.

• Each area displays one component (which could be another container such as a JPanel)

• If nothing is added to the outer areas, they take up no space and other areas expand to fill the void

• BorderLayout is good for maintaining a row of buttons in one of the areas

near the edges.

• BorderLayout has two constructors:o BorderLayout()o BorderLayout(int hgap, int vgap)

North

South

Center EastWest

Page 8: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 8

Example 3: Border Layout Test

1 import java.awt.*; import javax.swing.*; 2 public class TestBorderLayout extends TestGridLayout{ 3 public TestBorderLayout() { 4 setTitle("Border Layout Test."); 5 JPanel jp1 = (JPanel)getContentPane(); 6 JPanel jp2 = new JPanel(); 7 jp2.setLayout(new BorderLayout()); 8 9 jp2.add(new JButton("NORTH"), "North");10 jp2.add(new JButton("WEST"), "West");11 jp2.add(new JButton("EAST"), "East");12 jp2.add(new JButton("SOUTH"), "South");1314 jp2.add(jp1);15 setContentPane(jp2);16 setVisible(true);17 }18 public static void main(String args [] ) {19 new TestBorderLayout();20 }21 }

Page 9: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 9

Introduction to Box Layout

• A box layout organizes components either horizontally (in one row) or vertically (in one column).

• Components are placed top-to-bottom or left-to-right in the order in which they are added to the container.

• By combining multiple containers using box layout, many different configurations can be created.

• Invisible components can be added to a box layout container to take up space between components.

– Rigid areas have a fixed size

– Glue specifies where excess space should go.

• A rigid area is created using the createRigidArea method of the Box class

• Glue is created using the createHorizontalGlue or createVerticalGlue methods.

Page 10: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 10

BoxLayout

Page 11: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 11

Further GUI Programming Examples

• Example 1: Enhancing the Telephone Handset Example

• Example 2: Menu Test

• Example 3: File Dialog Test

• Example 4: Popup Menu Test

Page 12: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 12

Introduction to Example 1

• This example builds on Example 4 of the preceding section.

• Example 4 of the preceding section developed a simple GUI for

a telephone handset.

• We will now add event-handling code to display typed numbers.

• Here is a sample output of the program:

Page 13: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 13

Example 1: Flow Layout

1 import javax.swing.*; 2 class TestFlowLayout extends JFrame{ 3 JPanel panel = new JPanel(); 4 public TestFlowLayout(){ 5 panel.add(new JButton("1")); 6 panel.add(new JButton("2")); 7 panel.add(new JButton("3")); 8 panel.add(new JButton("4")); 9 panel.add(new JButton("5"));10 panel.add(new JButton("6"));11 panel.add(new JButton("7"));12 setContentPane(panel);13 setSize(300,300);14 setTitle("Flow Layout Test");15 setVisible(true);16 }17 public static void main(String [] args){18 new TestFlowLayout();19 }20 }

Note: we did not set the layout because Flow Layout is the default one for the panel

Page 14: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 14

Example 1: Grid Layout Test

1 import java.awt.*; import javax.swing.*; 2 import javax.swing.border.*; 3 class TestGridLayout extends TestFlowLayout{ 4 public TestGridLayout(){ 5 panel.add(new JButton("8")); 6 panel.add(new JButton("9")); 7 panel.add(new JButton("*")); 8 panel.add(new JButton("0")); 9 panel.add(new JButton("#"));10 JLabel jlb = new JLabel(“03-8604698", SwingConstants.CENTER);11 Border b

=BorderFactory.createBevelBorder(BevelBorder.RAISED);12 jlb.setBorder(BorderFactory.createTitledBorder(b,“Telephone"));13 panel.add(jlb);14 setTitle("Grid Layout Test");15 panel.setLayout(new GridLayout(0,3));16 setVisible(true);17 }18 public static void main(String [] args){19 new TestGridLayout();20 }21 }

Page 15: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 15

Example 1: The Telephone Handset

1 import java.awt.*; import javax.swing.*; import java.awt.event.*; 2 class TelephoneTest extends TestGridBagLayout implements ActionListener{ 4 public TelephoneTest(){ 5 Component components[] = getContentPane().getComponents(); 6 JPanel cancelPanel = (JPanel)components[13]; 7 JButton cancel = (JButton)cancelPanel.getComponent(0); 8 for(int i=0;i<components.length; i++){ 9 if(components[i] instanceof JButton)10 ((JButton)components[i]).addActionListener(this);11 }12 cancel.addActionListener(this);13 }14 public void actionPerformed(ActionEvent ae) {15 if (ae.getActionCommand().equals("Cancel"))16 display.setText("");17 else18 display.setText(display.getText()+ae.getActionCommand());19 }20 public static void main(String [] args){21 new TelephoneTest().setVisible(true);22 }}

Page 16: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 16

Introduction to Example 2

• In this example we demonstrate how menus, separator, mnemonic

and accelerators can be added into an application.

• The output of the example is as follows:

Page 17: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 17

Class Hierarchy for Menus

• Classes used to define menus are:

o JMenuBar

o JMenuItem

o JMenu

o JCheckButtonMenuItem

o JRadioButtonMenuItem

Page 18: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 18

Mnemonics

• A mnemonic provides a keyboard alternative for pushing a button or selecting a menu option.

• The mnemonic character should be chosen from the component's label, and is underlined.

• The user activates the component by holding down the ALT key and pressing the mnemonic character.

• A mnemonic is established using the setMnemonic method

JButton button = new JButton ("Calculate");

button.setMnemonic ("C");

Page 19: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 19

Example 2: Menus and Mnemonics

1 import java.awt.event.*; 2 import javax.swing.*; 3 class MenuTest extends JFrame { 4 private JMenuBar menuBar = new JMenuBar(); 5 protected JMenu fileMenu = new JMenu("File"); 6 protected JMenuItem neW, open, quit, save, print; 7 private JMenuItem saveCurrent, saveAs, saveAll; 8 MenuTest(String title){ 9 super(title);10 setJMenuBar(menuBar);11 menuBar.add(fileMenu);12 fileMenu.setMnemonic('F');13 fileMenu.add(neW = new JMenuItem ("New"));14 fileMenu.add(open = new JMenuItem ("Open"));15 open.setMnemonic('o');16 fileMenu.add(save = new JMenu ("Save"));17 save.add(saveCurrent = new JMenuItem ("Save Current"));18 save.add(saveAs = new JMenuItem ("Save As"));19 save.add(saveAll = new JMenuItem ("Save All"));20 fileMenu.add(save);21 fileMenu.add(print = new JCheckBoxMenuItem ("Print"));22 fileMenu.addSeparator();

Page 20: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 20

Menus and Mnemonics (cont’d)

23 fileMenu.add(quit = new JMenuItem("Quit"));24 quit.setMnemonic(KeyEvent.VK_Q);25 quit.setAccelerator(26 KeyStroke.getKeyStroke(KeyEvent.VK_Q,KeyEvent.CTRL_MASK));27 quit.addActionListener(new ActionListener(){28 public void actionPerformed(ActionEvent e){29 int result=JOptionPane.showConfirmDialog(MenuTest.this,30 "Quit/Close Menu Demos Window?");31 if (result == JOptionPane.YES_OPTION)32 System.exit(0);33 }34 });35 setSize(300,300);36 }37 public static void main(String args[]){38 MenuTest t = new MenuTest("Menus Test");39 t.setVisible(true);40 }41 }

Page 21: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 21

Introduction to Example 3

• This example extends Example 2 to launch a file dialog on selecting

the Open menu.

• The selected file name is simply printed on another display window.

• The output is as follows:

Page 22: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 22

Example 3: File Dialog Test

1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 class FileDialogTest extends MenuTest { 5 JEditorPane textPane= new JEditorPane(); 6 FileDialogTest(String title){ 7 super(title); 8 open.addActionListener( new ActionListener() { 9 public void actionPerformed(ActionEvent e ) {10 FileDialog fd = new FileDialog(FileDialogTest.this);11 fd.setVisible(true);12 textPane.setText("Selected file: "+fd.getFile());13 } });14 getContentPane().add(textPane);15 }16 public static void main(String args[]){17 FileDialogTest t = new FileDialogTest("File Dialog Test");18 t.setVisible(true);1920 }21 }

Page 23: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 23

Introduction to Example 4

• This example extends Example 2 of the preceding section to add pop-up menus..

• The output looks like:

• The menu consists of three colors that can be used to reset a component’s background color.

Page 24: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 24

Example 4: Popup Menu Test

1 import java.awt.*; import java.awt.event.*; import javax.swing.*; 2 public class PopupMenuTest extends TestGridLayout{ 3 Component selectedComponent; 4 JPopupMenu colorMenu = new JPopupMenu(); 5 JMenuItem blue, white, yellow; 6 public PopupMenuTest(){ 7 setTitle("Popup Menu Test"); 8 colorMenu.add(blue=new JMenuItem("Blue")); 9 colorMenu.add(white=new JMenuItem("White"));10 colorMenu.add(yellow=new JMenuItem("Yellow"));11 Component components[] = getContentPane().getComponents();12 class MyListener extends MouseAdapter {13 public void mousePressed(MouseEvent e){checkPopup(e);}14 public void mouseClicked(MouseEvent e){checkPopup(e);}15 public void mouseReleased(MouseEvent e){checkPopup(e);}16 public void checkPopup(MouseEvent e) {17 if (e.isPopupTrigger()){18 selectedComponent = e.getComponent();19 colorMenu.show(e.getComponent(),e.getX(),e.getY());20 }21 }22 }

Page 25: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 25

Popup Menu Test (cont’d)

23 MouseListener mylistener = new MyListener();24 for(int i=0;i<components.length-1; i++){25 JButton b = (JButton)components[i];26 b.addMouseListener(mylistener);27 }28 blue.addActionListener(new ActionListener () {29 public void actionPerformed(ActionEvent ae){30 selectedComponent.setBackground(Color.blue);31 }});32 white.addActionListener(new ActionListener() {33 public void actionPerformed(ActionEvent ae){34 selectedComponent.setBackground(Color.white);35 }});36 yellow.addActionListener(new ActionListener() {37 public void actionPerformed(ActionEvent ae){38 selectedComponent.setBackground(Color.yellow);39 }});40 }41 public static void main(String[] args) {42 new PopupMenuTest().setVisible(true);43 }44 }

Page 26: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 26

Exercises

1. Move the call to the setVisible() method from the main() method to the TetFlowLayout constructor in Example 1. Then compile and run each of Examples 2, 3 and 4. You will notice some changes when displaying the frames. Explain.

2. Modify Example 2 to add two other types of borders to it.3. Compare Example 2 and Example 3. In Example 2 we inherited a panel, added

more components to it and then changed the panel’ÿ layout manager. In Example 3 we had to create an additional panel. Can Example 3 be written in similar manner to Example 2 without the additional panel? If it is possible, write the equivalent program otherwise explain why it is not possible.

4. Change the fill constraint variable on Line 13 from BOTH to each of the following: NONE, HORIZONTAL and VERTICAL. Run the program in each case and study the effect.

5. Change the value of the gridy constraint variable on Lines 29 to a smaller value. Run the program and observe the result. Do the same for the value on Line 32. Also change these values to bigger values and observe the results.

Page 27: Unit 121 A layout manager is an object that determines the manner in which components are arranged in a container. Each layout manager implements one of

Unit 12 27

Review Exercises

1 What are the event sources and event listeners in Example 1?2 Can the event handler in Example 1 be implemented in a single

anonymous class? If not, why not?3 Modify Example 1 to use two inner classes instead of one. Can the two

inner classes both be anonymous? Is the program with one inner class better than the one with two? Explain.

4 Enhance Example 1 so that when the Redial button is pushed the last text displayed on the text component is displayed again.

5 Write a Java program to illustrate how a component event can be handled.

6 Modify Example 3 so that when a file is double-clicked from the file dialog window the file is opened rather than displaying its name in the editor pane.

7 When you run Example 4, you will find that the lower part of the window is not responding to the popup menu. Modify this program to ensure that that part of the window also responds to the popup menu events like the buttons in the window.