We recommend specifying the gridx and gridy values for each component; gridwidth, gridheight Specify the number of columns for gridwidth or rows for gridheight in the component's dis
Trang 1PHẦN 2 - SWING
LAYOUT MANAGEMENT
Trang 2Khoa CNTT – ĐH Nông Lâm TP HCM 2014 2/79
Introduction
Every container, by default, has a layout manager
an object that implements the LayoutManager
interface.* If a container's default layout manager
doesn't suit your needs, you can easily replace it
with another one The Java platform supplies layout managers that range from the very simple
(FlowLayout and GridLayout) to the special purpose (BorderLayout and CardLayout) to the very flexible (GridBagLayout and BoxLayout)
Trang 3 BorderLayout is the default layout manager for every content pane A BorderLayout has five areas available
to hold components: north , south , east , west , and
center All extra space is placed in the center area
Trang 4Khoa CNTT – ĐH Nông Lâm TP HCM 2014 4/79
BorderLayout
public class BorderLayoutFrame extends JFrame{
public BorderLayoutFrame(String title) {
super (title);
Container contentPane = getContentPane();
//Use the content pane's default BorderLayout.
contentPane.setLayout( new BorderLayout(2,2));
contPane.add( new JButton( "Button 1 (NORTH)" ),
Trang 5The BorderLayout API
By default, a BorderLayout puts no gap between the
components it manages In the preceding applet, any
apparent gaps are the result of the buttons reserving extra
space around their apparent display area You can specify gaps (in pixels) using the following constructor:
BorderLayout(int horizontalGap , int verticalGap )
You can also use the following methods to set the horizontal and vertical gaps, respectively:
void setHgap(int)
void setVgap(int)
Trang 6Khoa CNTT – ĐH Nông Lâm TP HCM 2014 6/79
FlowLayout
FlowLayout is the default layout manager for every JPanel It simply lays out components from left to right , starting new rows if necessary
Trang 7Container contentPane = getContentPane();
contentPane.setLayout( new FlowLayout());
contentPane.add( new JButton( "Button 1” );
contentPane.add( new JButton( "2" ));
contentPane.add( new JButton( "Button 3" ));
contentPane.add( new JButton( "Long-Named Button 4" )); contentPane.add( new JButton( "Button 5” );
pack();
Trang 8Khoa CNTT – ĐH Nông Lâm TP HCM 2014 8/79
The FlowLayout API
The FlowLayout class has three constructors:
public FlowLayout()
public FlowLayout(int alignment )
public FlowLayout(int alignment , int horizontalGap , int
verticalGap )
The alignment argument must have the value
FlowLayout.LEFT, FlowLayout.CENTER, or
FlowLayout.RIGHT The horizontalGap and
verticalGap arguments specify the number of pixels to put
between components If you don't specify a gap value,
FlowLayout uses 5 for the default gap value
Trang 9 GridLayout simply makes a bunch of components
equal in size and displays them in the requested
number of rows and columns Here's an applet that uses a GridLayout to control the display of five
buttons:
Trang 10Khoa CNTT – ĐH Nông Lâm TP HCM 2014 10/79
Trang 11The GridLayout API
The GridLayout class has two constructors:
public GridLayout(int rows , int columns )
public GridLayout(int rows , int columns , int
horizontalGap , int verticalGap )
At least one of the rows and columns
arguments must be non zero The horizontalGap
and verticalGap arguments to the second constructor allow you to specify the number of pixels between
cells If you don't specify gaps, their values default to zero In the applet above, any apparent gaps are the result of the buttons reserving extra space around
their apparent display area
Trang 12Khoa CNTT – ĐH Nông Lâm TP HCM 2014 12/79
GridBagLayout
GridBagLayout is the most sophisticated, flexible layout
manager the Java platform provides It aligns components by placing them within a grid of cells, allowing some
components to span more than one cell The rows in the grid aren't necessarily all the same height; similarly, grid columns can have different widths
Trang 13GridBagLayout : Specifying
Constraints
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
JPanel pane = new JPanel(); pane.setLayout(gridbag);
//For each component to be added to this
container: // Create the component
// Set instance variables in the GridBagConstraints
gridbag.setConstraints(theComponent, c);
pane.add(theComponent);
You can reuse the same GridBagConstraints instance for multiple components, even if the components have
different constraints The GridBagLayout extracts the
constraint values and doesn't use the GridBagConstraints again You must be careful, however, to reset the
GridBagConstraints instance variables to their default
values when necessary
Trang 14Khoa CNTT – ĐH Nông Lâm TP HCM 2014 14/79
GridBagLayout : Specifying
Constraints
gridx, gridy
Specify the row and column at the upper left of the
component The leftmost column has address gridx=0 and the top row has address gridy=0 Use
GridBagConstraints.RELATIVE (the default value) to specify
that the component be placed just to the right of (for gridx) or just below (for gridy) the component that was added to the container just before this component was added We
recommend specifying the gridx and gridy values for each
component;
gridwidth, gridheight
Specify the number of columns (for gridwidth) or rows (for
gridheight) in the component's display area These constraints specify the number of cells the component uses, not the
number of pixels it uses The default value is 1 Use
GridBagConstraints.REMAINDER to specify that the component
be the last one in its row (for gridwidth) or column (for
gridheight) Use GridBagConstraints.RELATIVE to specify that the component be the next to last one in its row (for
gridwidth) or column (for gridheight)
Trang 15GridBagLayout : Specifying
Constraints
fill
Used when the component's display area is larger than the
component's requested size to determine whether and how to resize the component Valid values (defined as
GridBagConstraints constants) are NONE (the default),
HORIZONTAL (make the component wide enough to fill its
display area horizontally, but don't change its height),
VERTICAL (make the component tall enough to fill its display area vertically, but don't change its width), and BOTH (make the component fill its display area entirely)
ipadx, ipady
Specifies the internal padding: how much to add to the
minimum size of the component The default value is zero
The width of the component will be at least its minimum width plus ipadx*2 pixels, since the padding applies to both sides of the component Similarly, the height of the component will be
Trang 16Khoa CNTT – ĐH Nông Lâm TP HCM 2014 16/79
GridBagLayout : Specifying
Constraints
insets
Specifies the external padding of the component the
minimum amount of space between the component and the edges of its display area The value is specified as an Insets object By default, each component has no external
padding
anchor
Used when the component is smaller than its display area to determine where (within the area) to place the component Valid values (defined as GridBagConstraints constants) are CENTER (the default), NORTH, NORTHEAST, EAST,
SOUTHEAST, SOUTH, SOUTHWEST, WEST, and
NORTHWEST
Trang 17GridBagLayout : Specifying
Constraints
weightx, weighty
appearance of the components a GridBagLayout controls Weights are used to determine how to distribute space among columns (weightx) and among rows (weighty); this is important for specifying resizing
behavior Unless you specify at least one nonzero value for weightx or weighty, all the components clump together in the center of their
container This is because when the weight is 0.0 (the default), the GridBagLayout puts any extra space between its grid of cells and the edges of the container
numbers in between are used as necessary Larger numbers indicate that the component's row or column should get more space For each column, the weight is related to the highest weightx specified for a
component within that column, with each multicolumn component's weight being split somehow between the columns the component is in Similarly, each row's weight is related to the highest weighty specified for a component within that row
Trang 18Khoa CNTT – ĐH Nông Lâm TP HCM 2014 18/79
Summary
gridx, gridy : Toạ độ (vị trí cột hàng)
gridwidth, gridheight : Chiều dài, chiều cao của đối tượng (Số cột, số dòng mà đối tượng sẽ hiển thị)
Fill : tự động resize đối tượng theo kích thước cử sổ hiện hành
ipadx, ipady: Số pixel cộng thêm vào chiều dài, cao của đối
tượng để đạt được kích thước tối thiểu MinWidth = TextWidth + ipadx*2
Insets: Khoảng cách giữa các đối tượng
Anchor: Vị trí (alignment) hiển thị của đối tượng khi vùng hiển thị > kích thước đối tượng
weightx, weighty : tỷ lệ (Kích thước tương đối) của các đối
tượng Weightx = 0 : đối tượng không resize theo bề rộng Các giá trị có thể từ 0.0-1.0
Trang 19JButton button;
Container contentPane = getContentPane();
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints(); contentPane.setLayout(gridbag);
Trang 20Khoa CNTT – ĐH Nông Lâm TP HCM 2014 20/79
button = new JButton("Long-Named Button 4");
c.ipady = 40; //make this component tall
Trang 21button = new JButton("Button 5");
c.ipady = 0; //reset to default
c.weighty = 1.0; //request any extra vertical space //bottom of space
c.anchor = GridBagConstraints.SOUTH;
//top padding
c.insets = new Insets(10,0,0,0);
c.gridx = 1; //aligned with button 2
c.gridwidth = 2; //2 columns wide
c.gridy = 2; //third row
gridbag.setConstraints(button, c);
contentPane.add(button);
Trang 22MAKE CHOICES
Trang 23How to Use Check Boxes
The JCheckBox class provides support for check box buttons You can also put check boxes in menus, using the
JCheckBoxMenuItem class Because JCheckBox and
JCheckBoxMenuItem inherit from AbstractButton, Swing check boxes have all the usual button characteristics
Check boxes are similar to
radio buttons but their
selection model is different,
by convention Any number
of check boxes in a group
none, some, or all can be
selected A group of radio
buttons, on the other hand,
can have only one button
selected
Trang 24Khoa CNTT – ĐH Nông Lâm TP HCM 2014 24/79
How to Use Check Boxes
public class CheckBoxDemo extends JPanel {
// Create the check boxes
chinButton = new JCheckBox("Chin");
chinButton.setMnemonic(KeyEvent.VK_C);
chinButton.setSelected(true);
glassesButton = new JCheckBox("Glasses");
glassesButton.setMnemonic(KeyEvent.VK_G);
glassesButton.setSelected(true);
Trang 25How to Use Check Boxes
hairButton = new JCheckBox( "Hair" );
// Register a listener for the check boxes.
CheckBoxListener myListener = new CheckBoxListener(); chinButton.addItemListener(myListener);
glassesButton.addItemListener(myListener);
hairButton.addItemListener(myListener);
teethButton.addItemListener(myListener);
Trang 26Khoa CNTT – ĐH Nông Lâm TP HCM 2014 26/79
How to Use Check Boxes
// Indicates what's on the geek.
choices = new StringBuffer( "cght" );
// Set up the picture label
pictureLabel = new JLabel( new ImageIcon(
"images/geek/geek-" + choices toString() + ".gif" )); pictureLabel setToolTipText( choices toString());
// Put the check boxes in a column in a panel
JPanel checkPanel = new JPanel();
checkPanel.setLayout( new GridLayout(0, 1));
checkPanel.add( chinButton );
checkPanel.add( glassesButton );
checkPanel.add( hairButton );
checkPanel.add( teethButton );
setLayout( new BorderLayout());
add(checkPanel, BorderLayout.WEST);
add( pictureLabel , BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
Trang 27How to Use Check Boxes
class CheckBoxListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
int index = 0; char c = '-' ;
Object source = e.getItemSelectable();
pictureLabel setIcon( new ImageIcon(
"images/geek/geek-" + choices toString() + ".gif" )); pictureLabel setToolTipText( choices toString());
}
}
Trang 28Khoa CNTT – ĐH Nông Lâm TP HCM 2014 28/79
How to Use Check Boxes
class CheckBoxListener implements ItemListener { public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
if (source == chinButton) {
// make a note of it
// make a note of it
// make a note of it
// make a note of it
}
if (e.getStateChange() == ItemEvent.DESELECTED)
// make a note of it
picture.setIcon(/* new icon */);
} }
Trang 29Creates an initially unselected check box with an icon.
JCheckBox(Icon icon, boolean selected)
Creates a check box with an icon and specifies whether or not it
is initially selected
JCheckBox(String text)
Creates an initially unselected check box with text
JCheckBox(String text, boolean selected)
Creates a check box with text and specifies whether or not it is
Trang 30Khoa CNTT – ĐH Nông Lâm TP HCM 2014 30/79
API : JCheckBox
JCheckBox(String text, Icon icon)
Creates an initially unselected check box with the specified
text and icon.
JCheckBox(String text, Icon icon, boolean selected)
Creates a check box with text and icon, and specifies whether
or not it is initially selected.
boolean isSelected ()
returns the state of the check box.
void setSelected(boolean state)
sets the check box to a new state.
Trang 31API : Interface ItemListener
public void itemStateChanged(
Trang 32Khoa CNTT – ĐH Nông Lâm TP HCM 2014 32/79
API : ItemEvent
public static final int ITEM_STATE_CHANGED
This event id indicates that an item's state changed
public static final int SELECTED
This state-change value indicates that an item was selected
public static final int DESELECTED
This state-change-value indicates that a selected item was
deselected
public int getStateChange()
Returns the type of state change (selected or deselected)
Trang 33How to Use Radio Buttons
Radio buttons are groups of buttons in which, by
convention, only one button at a time can be selected The Swing release supports radio buttons with the
JRadioButton and ButtonGroup classes To put a
radio button in a menu, use the JRadioButtonMenuItem class Radio buttons look similar to check boxes, but, by
convention, check boxes place no limits on how many items can be selected at a time
Trang 34Khoa CNTT – ĐH Nông Lâm TP HCM 2014 34/79
How to Use Radio Buttons
public class RadioButtonDemo extends JPanel {
static JFrame frame;
static String birdString = "Bird";
static String catString = "Cat";
static String dogString = "Dog";
static String rabbitString = "Rabbit";
static String pigString = "Pig";
JLabel picture;
public RadioButtonDemo() {
// Create the radio buttons
JRadioButton birdButton = new JRadioButton(birdString);
Trang 35How to Use Radio Buttons
JRadioButton dogButton = new JRadioButton(dogString);
// Group the radio buttons.
ButtonGroup group = new ButtonGroup();
Trang 36Khoa CNTT – ĐH Nông Lâm TP HCM 2014 36/79
How to Use Radio Buttons
// Register a listener for the radio buttons
RadioListener myListener = new RadioListener();
// Set up the picture label
picture = new JLabel(new ImageIcon("images/"
+ birdString + ".gif"));
// The preferred size is hard-coded to be the width of the
// widest image and the height of the tallest image
// A real program would compute this
picture.setPreferredSize(new Dimension(177, 122));
Trang 37How to Use Radio Buttons
// Put the radio buttons in a column in a panel
JPanel radioPanel = new JPanel();
radioPanel.setLayout( new GridLayout(0, 1));
radioPanel.add(birdButton); radioPanel.add(catButton);
radioPanel.add(dogButton); radioPanel.add(rabbitButton);
radioPanel.add(pigButton);
setLayout( new BorderLayout());
add(radioPanel, BorderLayout.WEST);
add( picture , BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
/** Listens to the radio buttons */
class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
picture setIcon( new ImageIcon( "images/"
+ e.getActionCommand() + ".gif" ));
}
Trang 38Khoa CNTT – ĐH Nông Lâm TP HCM 2014 38/79
JRadioButton(Icon icon, boolean selected)
Creates a radio button with the specified image and selection state, but
no text
JRadioButton(String text)
Creates an unselected radio button with the specified text
JRadioButton(String text, boolean selected)
Creates a radio button with the specified text and selection state
JRadioButton(String text, Icon icon)
Creates a radio button that has the specified text and image, and that is initially unselected
Creates a radio button that has the specified text, image, and selection state
Trang 39API: ButtonGroup
public ButtonGroup()
Creates a new ButtonGroup
public void add(AbstractButton b)
Adds the button to the group
public void remove(AbstractButton b)
Removes the button from the group
public int getButtonCount()
Returns the number of buttons in the group