June 23: Layout Management.

Download Report

Transcript June 23: Layout Management.

Why layout managers
• Can we perform layout without them?
– Yes. A container’s layout property can be set to null.
• Absolute positioning: specify size and position
of every component within that container.
– does not adjust well when the top-level container is resized
– does not adjust well to differences between users and
systems
1
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AbsoluteExampleApplet extends JApplet {
private Container container;
private FlowLayout layout;
public void init () {
container = getContentPane();
container.setLayout(null);
JButton ok = new JButton("OK");
ok.setBounds(50, 100, 80, 25);
container.add(ok);
JButton close = new JButton("Close");
close.setBounds(150, 100, 80, 25);
container.add(close);
}
}
2
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AbsoluteExample extends JFrame {
private Container container;
public AbsoluteExample() {
container = getContentPane();
container.setLayout(null);
JButton ok = new JButton("OK");
ok.setBounds(50, 100, 80, 25);
container.add(ok);
JButton close = new JButton("Close");
close.setBounds(150, 100, 80, 25);
container.add(close);
setSize(300, 250);
setVisible(true);
}
public static void main(String[] args) {
AbsoluteExample ex = new AbsoluteExample();
ex.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
3
What is a layout manager
• A layout manager is an object that implements the
LayoutManager interface and determines the size
and position of the components within a container.
• A container's layout manager has the final say on
the size and position of the components within the
container, even though Components can provide
size and alignment hints
4
Layout Managers
• Layout managers
–
–
–
–
–
Provided for arranging GUI components
Provide basic layout capabilities
Processes layout details
Programmer can concentrate on basic “look and feel”
Interface LayoutManager
– Lay out elements by their relative positions without using
distance units
5
Layout Management
– Each container has a layout manager that directs the
arrangement of its components
– Components are added to a container which uses a layout
manager to place them
– Three useful layout managers are:
1) Border layout
2) Flow layout
3) Grid layout
Page 6
6
Containers
• Top-level containers
• Jdialog
• Jframe
• Japplet
• Intermediate level containers
– E.g. Jpanel, JScrollPan, …
• Heavyweight vs Lightweigtht components
7
Layout managers.
Layout manager
FlowLayout
BorderLayout
GridLayout
Description
Default for java.awt.Applet, java.awt.Panel and
javax.swing.JPanel. Places components sequentially
(left to right) in the order they were added. It is also possible to
specify the order of the components using the Container
method add that takes a Component and an integer index
position as arguments.
Default for the content panes of JFrames (and other windows)
and JApplets. Arranges the components into five areas:
North, South, East, West and Center.
Arranges the components into rows and columns.
Layout managers.
8
FlowLayout
• FlowLayout
– Most basic layout manager (but NOT always the default
manager)
– GUI components placed in container from left to right
9
Flow Layout
• Components are added from left to right
panel = new JPanel();
panel.add(rateLabel);
panel.add(rateField);
panel.add(button);
panel.add(resultLabel);
• Most basic layout manager (but NOT always the
default manager)
10
1 // FlowLayoutDemo.java
2 // Demonstrating FlowLayout alignments.
3
4 // Java core packages
5 import java.awt.*;
6 import java.awt.event.*;
7
8 // Java extension packages
9 import javax.swing.*;
10
11 public class FlowLayoutDemo extends JFrame {
12
private JButton leftButton, centerButton, rightButton;
13
private Container container;
14
private FlowLayout layout;
15
16
// set up GUI and register button listeners
17
public FlowLayoutDemo()
18
{
19
super( "FlowLayout Demo" );
20
21
layout = new FlowLayout();
22
23
// get content pane and set its layout
Set
24
container = getContentPane();
25
container.setLayout( layout );
26
27
// set up leftButton and register listener
28
leftButton = new JButton( "Left" );
29
30
leftButton.addActionListener(
31
32
// anonymous inner class
33
new ActionListener() {
34
35
// process leftButton event
FlowLayoutDemo.java
Lines 21-25
layout as FlowLayout
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.LEFT );
// re-align attached components
layout.layoutContainer( container );
}
}
// end anonymous inner class
); // end call to addActionListener
FlowLayoutDemo.java
When user presses
Line 38
left JButton,
left
align components
Line 61
container.add( leftButton );
// set up centerButton and register listener
centerButton = new JButton( "Center" );
centerButton.addActionListener(
// anonymous inner class
new ActionListener() {
// process centerButton event
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.CENTER );
// re-align attached components
layout.layoutContainer( container );
}
}
);
container.add( centerButton );
When user presses
center JButton,
center components
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105 }
// set up rightButton and register listener
rightButton = new JButton( "Right" );
rightButton.addActionListener(
FlowLayoutDemo.java
// anonymous inner class
new ActionListener() {
// process rightButton event
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.RIGHT );
// re-align attached components
layout.layoutContainer( container );
}
}
);
container.add( rightButton );
setSize( 300, 75 );
setVisible( true );
}
// execute application
public static void main( String args[] )
{
FlowLayoutDemo application = new FlowLayoutDemo();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
// end class FlowLayoutDemo
Line 82
When user presses
right JButton,
right components
FlowLayoutDemo.java
Nested Classes
• Java allows to define a class within another class
– logically grouping classes that are only used in one place
– increase encapsulation
– lead to more readable and maintainable code
class OuterClass {
...
class NestedClass {
...
}
}
– Inner class: Non-static nested classes
15
Anonymous Inner Classes
•
•
•
•
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
make the code more concise
declare and instantiate a class at the same time.
do not have a name
use only once
centerButton.addActionListener(
// anonymous inner class
new ActionListener() {
// process centerButton event
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.CENTER );
// re-align attached components
layout.layoutContainer( container );
}
}
);
16
BorderLayout
• BorderLayout
– Arranges components into five regions
• NORTH
• SOUTH
• EAST
• WEST
• CENTER
(top of container)
(bottom of container)
(left of container)
(right of container)
(center of container)
17
Border Layout
• Components are placed toward areas of a
container
– NORTH, EAST, SOUTH, WEST, or CENTER
– Specify one when adding components
 The content pane of a JFrame
uses border layout by default
panel.setLayout(new BorderLayout());
panel.add(component, BorderLayout.NORTH);
Page 18
18
1 // BorderLayoutDemo.java
2 // Demonstrating BorderLayout.
3
4 // Java core packages
5 import java.awt.*;
BorderLayoutDemo.j
6 import java.awt.event.*;
ava
7
8 // Java extension packages
9 import javax.swing.*;
Lines 24-28
10
11 public class BorderLayoutDemo extends JFrame
12
implements ActionListener {
13
14
private JButton buttons[];
15
private String names[] = { "Hide North", "Hide South",
16
"Hide East", "Hide West", "Hide Center" };
17
private BorderLayout layout;
18
19
// set up GUI and event handling
20
public BorderLayoutDemo()
21
{
22
super( "BorderLayout Demo" );
23
24
layout = new BorderLayout( 5, 5 );
25
26
// get content pane and set its layout
Set layout as BorderLayout with
27
Container container = getContentPane();
28
container.setLayout( layout );
5-pixel horizontal and vertical gaps
29
30
// instantiate button objects
31
buttons = new JButton[ names.length ];
32
33
for ( int count = 0; count < names.length; count++ ) {
34
buttons[ count ] = new JButton( names[ count ] );
35
buttons[ count ].addActionListener( this );
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
}
// place buttons in BorderLayout; order not important
container.add( buttons[ 0 ], BorderLayout.NORTH );
container.add( buttons[ 1 ], BorderLayout.SOUTH );
container.add( buttons[ 2 ], BorderLayout.EAST );
container.add( buttons[ 3 ], BorderLayout.WEST );
container.add( buttons[ 4 ], BorderLayout.CENTER );
BorderLayoutDemo.j
Place JButtons in regions
ava
specified by BorderLayout
Lines 39-43
setSize( 300, 200 );
setVisible( true );
Lines 54-57
}
// handle button events
public void actionPerformed( ActionEvent event )
{
for ( int count = 0; count < buttons.length; count++ )
if ( event.getSource() == buttons[ count ] )
buttons[ count ].setVisible( false );
else
buttons[ count ].setVisible( true );
When JButtons are “invisible,”
they are not displayed on screen,
and BorderLayout rearranges
// re-layout the content pane
layout.layoutContainer( getContentPane() );
}
// execute application
public static void main( String args[] )
{
BorderLayoutDemo application = new BorderLayoutDemo();
67
68
69
70
71
72 }
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
// end class BorderLayoutDemo
BorderLayoutDemo.j
ava
BorderLayoutDemo.j
ava
Grid Layout
• Divides container into grid of specified row and
columns
– Specify the size (rows then columns) of the grid
buttonPanel.setLayout(new GridLayout(4, 3));
Components are added starting at
top-left cell
Proceed left-to-fight until row is full
buttonPanel.add(button7);
buttonPanel.add(button8);
buttonPanel.add(button9);
buttonPanel.add(button4);
. . .
23
1 // GridLayoutDemo.java
2 // Demonstrating GridLayout.
3
4 // Java core packages
GridLayoutDemo.java
5 import java.awt.*;
6 import java.awt.event.*;
7
Line 27
8 // Java extension packages
9 import javax.swing.*;
Line 28
10
11 public class GridLayoutDemo extends JFrame
12
implements ActionListener {
13
14
private JButton buttons[];
15
private String names[] =
16
{ "one", "two", "three", "four", "five", "six" };
17
private boolean toggle = true;
18
private Container container;
19
private GridLayout grid1, grid2;
20
21
// set up GUI
22
public GridLayoutDemo()
23
{
24
super( "GridLayout Demo" );
Create GridLayout grid1
25
with 2 rows and 3 columns
26
// set up layouts
27
grid1 = new GridLayout( 2, 3, 5, 5 );
28
grid2 = new GridLayout( 3, 2 );
Create GridLayout grid2
29
with 3 rows and 2 columns
30
// get content pane and set its layout
31
container = getContentPane();
32
container.setLayout( grid1 );
33
34
// create and add buttons
35
buttons = new JButton[ names.length ];
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68 }
for ( int count =
buttons[ count
buttons[ count
container.add(
}
0; count < names.length; count++ ) {
] = new JButton( names[ count ] );
].addActionListener( this );
buttons[ count ] );
setSize( 300, 150 );
setVisible( true );
}
// handle button events by toggling between layouts
public void actionPerformed( ActionEvent event )
{
if ( toggle )
Toggle current
container.setLayout( grid2 );
GridLayout when
else
user presses JButton
container.setLayout( grid1 );
toggle = !toggle;
// set toggle to opposite value
container.validate();
}
// execute application
public static void main( String args[] )
{
GridLayoutDemo application = new GridLayoutDemo();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
// end class GridLayoutDemo
GridLayoutDemo.java
Lines 50-53
GridLayoutDemo.java
Panels
• Panel
– Helps organize components
– Class JPanel is JComponent subclass
– May have components (and other panels) added to them
27
1 // PanelDemo.java
2 // Using a JPanel to help lay out components.
3
4 // Java core packages
5 import java.awt.*;
PanelDemo.java
6 import java.awt.event.*;
7
Line 27
8 // Java extension packages
9 import javax.swing.*;
10
Line 35
11 public class PanelDemo extends JFrame {
12
private JPanel buttonPanel;
13
private JButton buttons[];
14
15
// set up GUI
16
public PanelDemo()
17
{
18
super( "Panel Demo" );
19
20
// get content pane
21
Container container = getContentPane();
22
23
// create buttons array
24
buttons = new JButton[ 5 ];
25
26
// set up panel and set its layout
27
buttonPanel = new JPanel();
Create JPanel to hold JButtons
28
buttonPanel.setLayout(
29
new GridLayout( 1, buttons.length ) );
30
31
// create and add buttons
32
for ( int count = 0; count < buttons.length; count++ ) {
33
buttons[ count ] =
34
new JButton( "Button " + ( count + 1 ) );
35
buttonPanel.add( buttons[ count ] );
Add JButtons to JPanel
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53 }
}
container.add( buttonPanel, BorderLayout.SOUTH );
setSize( 425, 150 );
setVisible( true );
}
// execute application
public static void main( String args[] )
{
PanelDemo application = new PanelDemo();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
// end class PanelDemo
PanelDemo.java
Add JPanel to SOUTH
region of Container
Line 38
Content Pane
• The content pane
– The container of the root pane's visible components,
excluding the menu bar
– Using a Jpanel
https://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html
30
Using Nested Panels
• Create complex layouts by nesting panels
– Give each panel an appropriate layout manager
– Panels have invisible borders, so you can use as many
panels as you need to organize components
JTextField in NORTH of keypadPanel
JPanel GridLayout in CENTER of keypadPanel
JPanel keypadPanel = new JPanel();
keypadPanel.setLayout(new BorderLayout());
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 3));
buttonPanel.add(button7);
buttonPanel.add(button8);
// . . .
keypadPanel.add(buttonPanel, BorderLayout.CENTER);
JTextField display = new JTextField();
keypadPanel.add(display, BorderLayout.NORTH);
31
Other layout managers
• Layout managers are not limited to
– FlowLayout
– GridLayout
– BorderLayout
• Other
–
–
–
–
–
BoxLayout
CardLayout
GridBagLayout
GroupLayout
SpringLayout
32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// CardDeck.java
// Demonstrating CardLayout.
// Java core packages
import java.awt.*;
import java.awt.event.*;
CardDeck.java
Lines 16-17
// Java extension packages
import javax.swing.*;
Lines 28-29
public class CardDeck extends JFrame implements ActionListener {
private CardLayout cardManager;
private JPanel deck;
private JButton controls[];
private String names[] = { "First card", "Next card",
"Previous card", "Last card" };
Card names
// set up GUI
public CardDeck()
{
super( "CardLayout " );
Container container = getContentPane();
// create the JPanel with CardLayout
deck = new JPanel();
cardManager = new CardLayout();
deck.setLayout( cardManager );
Set CardLayout
as layout manager
for JPanel deck
33
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// set up card1 and add it to JPanel deck
JLabel label1 =
new JLabel( "card one", SwingConstants.CENTER );
JPanel card1 = new JPanel();
card1.add( label1 );
deck.add( card1, label1.getText() ); // add card to deck
// set up card2 and add it to JPanel deck
JLabel label2 =
new JLabel( "card two", SwingConstants.CENTER );
JPanel card2 = new JPanel();
card2.setBackground( Color.yellow );
card2.add( label2 );
deck.add( card2, label2.getText() ); // add card to deck
Create first card as
CardDeck.java
JPanel
and add to deck
Lines 32-36
Create
second
card as
Lines
39-44
JPanel with yellow
background
and47-55
add to deck
Lines
Lines 58-66
Create third card as JPanel
with BorderLayout and
add to deck
// set up card3 and add it to JPanel deck
JLabel label3 = new JLabel( "card three" );
JPanel card3 = new JPanel();
card3.setLayout( new BorderLayout() );
card3.add( new JButton( "North" ), BorderLayout.NORTH );
card3.add( new JButton( "West" ), BorderLayout.WEST );
card3.add( new JButton( "East" ), BorderLayout.EAST );
card3.add( new JButton( "South" ), BorderLayout.SOUTH );
card3.add( label3, BorderLayout.CENTER );
deck.add( card3, label3.getText() ); // add card to deck
// create and layout buttons that will control deck
JPanel buttons = new JPanel();
buttons.setLayout( new GridLayout( 2, 2 ) );
controls = new JButton[ names.length ];
Create fourth card as
JPanel with GridLayout
and add to deck
for ( int count = 0; count < controls.length; count++ ) {
controls[ count ] = new JButton( names[ count ] );
controls[ count ].addActionListener( this );
buttons.add( controls[ count ] );
34
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
}
// add JPanel deck and JPanel buttons to the applet
container.add( buttons, BorderLayout.WEST );
container.add( deck, BorderLayout.EAST );
setSize( 450, 200 );
setVisible( true );
}
CardDeck.java
Lines 81-94
// end constructor
// handle button events by switching cards
public void actionPerformed( ActionEvent event )
{
// show first card
if ( event.getSource() == controls[ 0 ] )
cardManager.first( deck );
// show next card
else if ( event.getSource() == controls[ 1 ] )
cardManager.next( deck );
// show previous card
else if ( event.getSource() == controls[ 2 ] )
cardManager.previous( deck );
Switch card in deck,
depending on JButton
pressed by user
// show last card
else if ( event.getSource() == controls[ 3 ] )
cardManager.last( deck );
}
35
97
98
99
100
101
102
103
104
105
106
// execute application
public static void main( String args[] )
{
CardDeck cardDeckDemo = new CardDeck();
CardDeck.java
cardDeckDemo.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
}
// end class CardDeck
Program Output
36
Steps to Design a User Interface
1) Make a sketch of the component layout.
– Draw all the buttons, labels, text fields, and borders on a sheet of
graph paper
37
Steps to Design a User
Interface
2) Find groupings of adjacent components with the same
layout.
– Start by looking at adjacent components that are arranged top to
bottom or left to right
38
Steps to Design a User Interface
3) Identify layouts for each group.
– For horizontal components, use flow Layout
– For vertical components, use a grid layout with one column
4) Group the groups together.
– Look at each group as one blob, and group the blobs
together into larger groups, just as you grouped the
components in the preceding step
39
Steps to Design a User Interface
5) Write the code to generate the layout
JPanel radioButtonPanel = new JPanel();
radioButtonPanel.setLayout(new GridLayout(3, 1));
radioButton.setBorder(new TitledBorder(new EtchedBorder(), "Size"));
radioButtonPanel.add(smallButton);
radioButtonPanel.add(mediumButton);
radioButtonPanel.add(largeButton);
JPanel checkBoxPanel = new JPanel();
checkBoxPanel.setLayout(new GridLayout(2, 1));
checkBoxPanel.add(pepperoniButton());
checkBoxPanel.add(anchoviesButton());
JPanel pricePanel = new JPanel(); // Uses FlowLayout by default
pricePanel.add(new JLabel("Your Price:"));
pricePanel.add(priceTextField);
JPanel centerPanel = new JPanel(); // Uses FlowLayout
centerPanel.add(radioButtonPanel);
centerPanel.add(checkBoxPanel);
// Frame uses BorderLayout by default
add(centerPanel, BorderLayout.CENTER);
add(pricePanel, BorderLayout.SOUTH);
40
Summary: Containers and Layouts
• User-interface components are arranged by placing
them inside containers
– Containers can be placed inside larger containers
– Each container has a layout manager that directs the
arrangement of its components
– Three useful layout managers are the border layout, flow
layout, and grid layout.
– When adding a component to a container with the border
layout, specify the NORTH, EAST, SOUTH, WEST, or
CENTER position
• The content pane of a frame has a border layout by
default
• A panel has a flow layout by default
41
Applets and Stand-alone Applications
• It is possible to write Java applications in such a
way that they can be executed both as stand-alone
or applets
– Java applets usually don't have a main method
– Execute with a main method and call the init() and start()
method of the applet.
42
import java.awt.*;
import javax.swing.*;
public class BubbleSort extends JApplet {
public void init() {
JTextArea outputArea = new JTextArea();
Container container = getContentPane();
container.add( outputArea );
int array[] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
String output = "Data items in original order\n";
// append original array values to String output
for ( int counter = 0; counter < array.length; counter++ )
output += "
" + array[ counter ];
bubbleSort( array ); // sort array
output += "\n\nData items in ascending order\n";
// append sorted array values to String output
for ( int counter = 0; counter < array.length; counter++ )
output += "
" + array[ counter ];
outputArea.setText( output );
setSize( 375, 200 );
setVisible( true );
}
// sort elements of array with bubble sort
public void bubbleSort( int array2[] )
{
// loop to control number of passes
for ( int pass = 1; pass < array2.length; pass++ ) {
// loop to control number of comparisons
for ( int element = 0; element < array2.length - 1; element++ )
{
// compare side-by-side elements and swap them if first element is
//greater than second element
if ( array2[ element ] > array2[ element + 1 ] )
swap( array2, element, element + 1 );
}
}
}
}
// swap two elements of an array
public void swap( int array3[], int first, int second ) {
int hold; // temporary holding area for swap
hold = array3[ first ];
array3[ first ] = array3[ second ];
array3[ second ] = hold;
}
public static void main( String args[] )
{
JFrame app = new JFrame (“An applet running as an application”);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BubbleSort applet = new BubbleSort ();
applet.init();
applet.start();
// attach applet to the center of the window
app.getContentPane().add(applet);
app.setSize(375, 200);
app.setVisible(true);
}
// end class BubbleSort