Java GUI (V-VI)

Download Report

Transcript Java GUI (V-VI)

Laying Out Components
Within a Container
Doing Without a Layout Manager
(Absolute Positioning)
•
•
•
Set the container's layout manager to
null by calling setLayout(null).
Call the Component class's setbounds
method for each of the container's
children.
Call the Component class's repaint
method.
pane.setLayout(null);
JButton b1 = new JButton("one");
JButton b2 = new JButton("two");
JButton b3 = new JButton("three");
pane.add(b1);
pane.add(b2);
pane.add(b3);
Insets insets = pane.getInsets();
Dimension size = b1.getPreferredSize();
b1.setBounds(25 + insets.left, 5 + insets.top, size.width,
size.height);
size = b2.getPreferredSize();
b2.setBounds(55 + insets.left, 40 + insets.top, size.width,
size.height);
size = b3.getPreferredSize();
b3.setBounds(150 + insets.left, 15 + insets.top, size.width + 50,
size.height + 20);
Using Layout Managers
•
•
•
•
•
Setting the Layout Manager
Adding Components to a Container
Providing Size and Alignment Hints
Putting Space Between Components
Setting the Container's Orientation
Setting the Layout Manager
• As a rule, the only containers whose layout
managers you need to worry about are
JPanels and content panes.
• Each JPanel object is initialized to use a
FlowLayout, unless you specify differently
when creating the JPanel.
• Content panes use BorderLayout by default.
Setting the Layout Manager
JPanel panel = new JPanel(new BorderLayout());
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
Adding Components to a
Container
• When you add components to a panel or
content pane, the arguments you specify
to the add method depend on the layout
manager that the panel or content pane is
using.
pane.add(aComponent,
BorderLayout.PAGE_START);
Providing Size & Alignment Hints
• Sometimes you need to customize the size hints that a
component provides to its container's layout manager,
so that the component will be laid out well.
• You can do this by specifying one or more of the
minimum, preferred, and maximum sizes of the
component: setMinimumSize(), setPreferredSize(), and
setMaximumSize()
component.setMaximumSize(new Dimension(Integer.MAX_VALUE,
Integer.MAX_VALUE));
Putting Space Between
Components
• The layout manager
• Invisible components
• Empty borders
JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createLineBorder(Color.black));
Setting Container's Orientation
• To set a container's orientation, you
can use either the Component-defined
method setComponentOrientation or,
to set the orientation on the container's
children as well,
applyComponentOrientation.
How Layout Management Works
•
After the GUI is constructed, the pack method is invoked on the JFrame.
This specifies that the frame should be at its preferred size.
•
To find the frame's preferred size, the frame's layout manager adds the
size of the frame's edges to the preferred size of the component directly
contained by the frame. (the sum of the preferred size of the frame's
content pane, plus the size of the frame's menu bar, if any.)
•
The content pane's layout manager is responsible for figuring out the
content pane's preferred size.
•
When a component in the content pane is asked for its preferred size, the
default implementation (used by most components) first checks whether
the user specified a preferred size. If so, it reports that size. If not, it
queries its look and feel for the preferred size.
AWT and Swing classes provide
layout managers
•
•
•
•
•
•
•
•
BorderLayout
BoxLayout
CardLayout
FlowLayout
GridBagLayout
GridLayout
GroupLayout
SpringLayout
FlowLayout
The FlowLayout class puts components in a row, sized at their preferred size.
If the horizontal space in the container is too small to put all the components in
one row, the FlowLayout class uses multiple rows. If the container is wider
than necessary for a row of components, the row is, by default, centered
horizontally within the container.
FlowLayout experimentLayout = new FlowLayout();
...
compsToExperiment.setLayout(experimentLayout);
compsToExperiment.add(new JButton("Button 1"));
compsToExperiment.add(new JButton("Button 2"));
compsToExperiment.add(new JButton("Button 3"));
compsToExperiment.add(new JButton("Long-Named
Button 4"));
compsToExperiment.add(new JButton("5"));
// Fig. 11.39: FlowLayoutFrame.java
// Demonstrating FlowLayout alignments.
import java.awt.FlowLayout;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
public class FlowLayoutFrame extends JFrame
{
private JButton leftJButton; // button to set alignment left
private JButton centerJButton; // button to set alignment center
private JButton rightJButton; // button to set alignment right
private FlowLayout layout; // layout object
private Container container; // container to set layout
// set up GUI and register button listeners
public FlowLayoutFrame()
{
super( "FlowLayout Demo" );
layout = new FlowLayout(); // create FlowLayout
container = getContentPane(); // get container to layout
setLayout( layout ); // set frame layout
// set up leftJButton and register listener
leftJButton = new JButton( "Left" ); // create Left button
add( leftJButton ); // add Left button to frame
leftJButton.addActionListener(
new ActionListener() // anonymous inner class
{
// process leftJButton event
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.LEFT );
// realign attached components
layout.layoutContainer( container );
} // end method actionPerformed
} // end anonymous inner class
); // end call to addActionListener
// set up centerJButton and register listener
centerJButton = new JButton( "Center" ); // create Center button
add( centerJButton ); // add Center button to frame
centerJButton.addActionListener(
new ActionListener() // anonymous inner class
{
// process centerJButton event
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.CENTER );
// realign attached components
layout.layoutContainer( container );
} // end method actionPerformed
} // end anonymous inner class
); // end call to addActionListener
// set up rightJButton and register listener
rightJButton = new JButton( "Right" ); // create Right button
add( rightJButton ); // add Right button to frame
rightJButton.addActionListener(
new ActionListener() // anonymous inner class
{
// process rightJButton event
public void actionPerformed( ActionEvent event )
{
layout.setAlignment( FlowLayout.RIGHT );
// realign attached components
layout.layoutContainer( container );
} // end method actionPerformed
} // end anonymous inner class
); // end call to addActionListener
} // end FlowLayoutFrame constructor
} // end class FlowLayoutFrame
BorderLayout
A BorderLayout places components in up to five areas:
top, bottom, left, right, and center.
All extra space is placed in the center area.
These areas are specified by the
BorderLayout constants:
•
•
•
•
•
PAGE_START
PAGE_END
LINE_START
LINE_END
CENTER
•
•
•
•
•
NORTH
SOUTH
WEST
EAST
CENTER
setlayout(new BorderLayout());
JButton button = new JButton("Button 1 (PAGE_START)");
add(button, BorderLayout.PAGE_START);
//Make the center component big, since that's the
//typical usage of BorderLayout.
button = new JButton("Button 2 (CENTER)");
button.setPreferredSize(new Dimension(200, 100));
add(button, BorderLayout.CENTER);
button = new JButton("Button 3 (LINE_START)");
add(button, BorderLayout.LINE_START);
button = new JButton("Long-Named Button 4 (PAGE_END)");
add(button, BorderLayout.PAGE_END);
button = new JButton("5 (LINE_END)");
add(button, BorderLayout.LINE_END);
// Fig. 11.41: BorderLayoutFrame.java
// Demonstrating BorderLayout.
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
public class BorderLayoutFrame extends JFrame implements ActionListener
{
private JButton buttons[]; // array of buttons to hide portions
private final String names[] = { "Hide North", "Hide South",
"Hide East", "Hide West", "Hide Center" };
private BorderLayout layout; // borderlayout object
// set up GUI and event handling
public BorderLayoutFrame()
{
super( "BorderLayout Demo" );
layout = new BorderLayout( 5, 5 ); // 5 pixel gaps
setLayout( layout ); // set frame layout
buttons = new JButton[ names.length ]; // set size of array
// create JButtons and register listeners for them
for ( int count = 0; count < names.length; count++ )
{
buttons[ count ] = new JButton( names[ count ] );
buttons[ count ].addActionListener( this );
} // end for
add( buttons[ 0 ], BorderLayout.NORTH ); // add button to north
add( buttons[ 1 ], BorderLayout.SOUTH ); // add button to south
add( buttons[ 2 ], BorderLayout.EAST ); // add button to east
add( buttons[ 3 ], BorderLayout.WEST ); // add button to west
add( buttons[ 4 ], BorderLayout.CENTER ); // add button to center
} // end BorderLayoutFrame constructor
// handle button events
public void actionPerformed( ActionEvent event )
{
// check event source and layout content pane correspondingly
for ( JButton button : buttons )
{
if ( event.getSource() == button )
button.setVisible( false ); // hide button clicked
else
button.setVisible( true ); // show other buttons
} // end for
layout.layoutContainer( getContentPane() ); // layout content pane
} // end method actionPerformed
} // end class BorderLayoutFrame
GridLayout
A GridLayout object places components in a grid of cells. Each component takes
all the available space within its cell, and each cell is exactly the same size.
If the GridLayoutDemo window is resized, the GridLayout object changes the cell
size so that the cells are as large as possible, given the space available to the containe
GridLayout experimentLayout = new GridLayout(0,2);
...
compsToExperiment.setLayout(experimentLayout);
compsToExperiment.add(new JButton("Button 1"));
compsToExperiment.add(new JButton("Button 2"));
compsToExperiment.add(new JButton("Button 3"));
compsToExperiment.add(new JButton("Long-Named
Button 4"));
compsToExperiment.add(new JButton("5"));
// Fig. 11.43: GridLayoutFrame.java
// Demonstrating GridLayout.
import java.awt.GridLayout;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
public class GridLayoutFrame extends JFrame implements ActionListener
{
private JButton buttons[]; // array of buttons
private final String names[] =
{ "one", "two", "three", "four", "five", "six" };
private boolean toggle = true; // toggle between two layouts
private Container container; // frame container
private GridLayout gridLayout1; // first gridlayout
private GridLayout gridLayout2; // second gridlayout
// no-argument constructor
public GridLayoutFrame()
{
super( "GridLayout Demo" );
gridLayout1 = new GridLayout( 2, 3, 5, 5 ); // 2 by 3; gaps of 5
gridLayout2 = new GridLayout( 3, 2 ); // 3 by 2; no gaps
container = getContentPane(); // get content pane
setLayout( gridLayout1 ); // set JFrame layout
buttons = new JButton[ names.length ]; // create array of JButtons
for ( int count = 0; count < names.length; count++ )
{
buttons[ count ] = new JButton( names[ count ] );
buttons[ count ].addActionListener( this ); // register listener
add( buttons[ count ] ); // add button to JFrame
} // end for
} // end GridLayoutFrame constructor
// handle button events by toggling between layouts
public void actionPerformed( ActionEvent event )
{
if ( toggle )
container.setLayout( gridLayout2 ); // set layout to second
else
container.setLayout( gridLayout1 ); // set layout to first
toggle = !toggle; // set toggle to opposite value
container.validate(); // re-layout container
} // end method actionPerformed
} // end class GridLayoutFrame
BoxLayout
BoxLayout either stacks its components on top of each other
or places them in a row — your choice.
setLayout(new BoxLayout(pane,BoxLayout.Y_AXIS));
JButton button1 = new JButton("Button 1”);
button1.setAlignment(Component.CENTER_ALIGNMENT);
add(button1);
JButton button2 = new JButton("Button 2”);
button2.setAlignment(Component.CENTER_ALIGNMENT);
add(button1);
JButton button3 = new JButton("Button 3”);
button3.setAlignment(Component.CENTER_ALIGNMENT);
add(button1);
JButton button4 = new JButton("Long-Named Button 4”);
button4.setAlignment(Component.CENTER_ALIGNMENT);
add(button1);
JButton button5 = new JButton("5”);
button5.setAlignment(Component.CENTER_ALIGNMENT);
add(button1);
GridBagLayout
A GridBagLayout places components in a grid of rows and columns,
allowing specified components to span multiple rows or columns.
Not all rows necessarily have the same height. Similarly, not all columns
necessarily have the same width. Essentially, GridBagLayout places
components in rectangles (cells) in a grid, and then uses the components'
preferred sizes to determine how big the cells should be.
CardLayout
The CardLayout class manages two or more components
(usually JPanel instances) that share the same display space.
LayoutManager interface
•
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.
•
Dimension minimumLayoutSize(Container)
– Called by the Container getMinimumSize method, which is itself called under a
variety of circumstances.
•
void layoutContainer(Container)
– Called to position and size each of the components in the container.