Tải bản đầy đủ - 0 (trang)
Chapter 11. Specialty Panes and Layout Managers

Chapter 11. Specialty Panes and Layout Managers

Tải bản đầy đủ - 0trang

This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



I l@ve RuBoard



11.1 The JSplitPane Class

The JSplitPane component allows you to place two (and only two) components side by side in a single pane. You

can separate the pane horizontally or vertically, and the user can adjust this separator graphically at runtime. You

have probably seen such a split pane approach in things like a file chooser or a news reader. The top or left side

holds the list of directories or news subject lines while the bottom (or right side) contains the files or body of the

currently selected directory or article. To get started, Figure 11-2 shows a simple split pane example that shows two

text areas with a horizontal split. You can adjust the width of the split by grabbing the divider and sliding it left or right.



Figure 11-2. Simple JSplitPane with two text areas



Even with the code required to make the text areas behave (more on that in Chapter 19), the following example is still

fairly simple. If you are looking to get up and running with a quick split pane, this is the way to go.



// SimpleSplitPane.java

// A quick test of the JSplitPane class

//

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class SimpleSplitPane extends JFrame {



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



static String sometext = "This is a simple text string that is long enough " +

"to wrap over a few lines in the simple demo we're about to build. We'll " +

"put two text areas side by side in a split pane.";

public SimpleSplitPane( ) {

super("Simple SplitPane Frame");

setSize(450, 200);

setDefaultCloseOperation(EXIT_ON_CLOSE);

JTextArea jt1 = new JTextArea(sometext);

JTextArea jt2 = new JTextArea(sometext);

// Make sure our text boxes do line wrapping and have reasonable minimum sizes.

jt1.setLineWrap(true);

jt2.setLineWrap(true);

jt1.setMinimumSize(new Dimension(150, 150));

jt2.setMinimumSize(new Dimension(150, 150));

jt1.setPreferredSize(new Dimension(250, 200));

JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jt1, jt2);

getContentPane( ).add(sp, BorderLayout.CENTER);

}

public static void main(String args[]) {

SimpleSplitPane ssb = new SimpleSplitPane( );

ssb.setVisible(true);

}

}



11.1.1 Properties

Table 11-1 shows the properties contained in theJSplitPane class.



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



.



Table 11-1. JSplitPane properties

Property



Data type



get is set



accessibleContexto



AccessibleContext ·



bottomComponent



Component



b



b,*



JSplitPane.AccessibleJSplitPane(

)



·



boolean



continuousLayout



Default value



·



·



null



·



false



int



·



·



-1



int



·



·



5



lastDividerLocation



int



·



·



0



leftComponent



Component



·



·



null



maximumDividerLocation*



int



·



-1



minimumDividerLocation*



int



·



-1



dividerLocation

dividerSize



b



oneTouchExpandable



b



b



boolean



·



·



false



int



·



·



HORIZONTAL_SPLIT



double



·



·



0.0



rightComponent



Component



·



·



null



topComponent



Component



·



·



null



SplitPaneUI



·



From L&F



String



·



"SplitPaneUI"



orientation



resizeWeight



b, 1.3



b



UI



o



UIClassID

1.3



b



o



since 1.3, bound, overridden



*These properties return -1 only if no UI is

defined for this component. Normally, the UI is

queried for its current value.

See also properties from the JComponent class

(Table 3-6).



The properties of JSplitPane primarily relate to the divider. You can get and set its size, location, and orientation,

and its minimum and maximum bounds. Of particular interest is the oneTouchExpandable property. If this value is

set to true, the UI should provide a component that can quickly collapse or expand the divider. For your programming

convenience, four component properties are available. Note that the component properties bottomComponent

and rightComponent refer to the same object, as dotopComponent and leftComponent. This way, you can refer

to your components in a fashion that's consistent with the orientation of your split pane. The resizeWeight property

affects how new space is allocated if the split pane itself is resized. The default of 0.0 distributes all of the size

change to the bottom-right component; 1.0 goes entirely to the top-left component. If thecontinuousLayout

property is true, both sides of the pane are updated as often as possible while the user moves the divider. Otherwise,

the components are resized and redrawn only after the divider location is set. Continuous layout can be a

performance problem and is often just awkward. The lastDividerLocation property saves the previous location of



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



the divider and can be used to undo a change in the divider's position.



11.1.2 Constants

Several constants are defined for use with the JSplitPane class (see Table 11-2). Some of these constants name

the various properties in a split pane while others provide constraints for where to place a component or where to

place the split.



Table 11-2. JSplitPane constants

Constant



Type



Description



BOTTOM



String Add a component to the bottom of a vertically split pane.



CONTINUOUS_LAYOUT_PROPERTY



String



DIVIDER



String Add a component as the divider for the pane.

1.3



DIVIDER_LOCATION_PROPERTY



String



DIVIDER_SIZE_PROPERTY



String



Used in property change events to specify that the



continuousLayout property has been changed.



Used in property change events to specify that the



dividerLocation property has changed.

Used in property change events to specify that the dividerSize

property has changed.

One of the valid values for the orientation property of a



HORIZONTAL_SPLIT



int



JSplitPane object. This type of split creates a vertical divider,

resulting in a set of left/right components.

Used in property change events to specify that the



LAST_DIVIDER_LOCATION_PROPERTY



String



LEFT



String Add a component to the left of a horizontally split pane.



ONE_TOUCH_EXPANDABLE_PROPERTY String



ORIENTATION_PROPERTY



RESIZE_WEIGHT_PROPERTY



String



1.3



String



lastDividerLocation property has changed.



Used in property change events to specify that the



oneTouchExpandable property has changed.

Used in property change events to specify that the orientation

property has changed.

Used in property change events to specify that the



resizeWeight property has changed.



RIGHT



String Add a component to the right of a horizontally split pane.



TOP



String Add a component to the top of a vertically split pane.



VERTICAL_SPLIT



int



One of the valid values for the orientation property of a



JSplitPane object. This type of split creates a horizontal

divider, resulting in a set of top/bottom components.



1.3



since 1.3



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



.



11.1.3 Constructors

public JSplitPane( )

This constructor is a "demo" constructor. It sets up a horizontal split with a left button and right button (both



JButton components) already defined and added.

public JSplitPane(int orientation)

public JSplitPane(int orientation, boolean continuousLayout)

These constructors allow you to pick your initial split (horizontal or vertical) using the constants



HORIZONTAL_SPLIT and VERTICAL_SPLIT. No components are added to either pane. If you give a

true value as thecontinuousLayout argument to the second constructor, both panes are repainted

continuously as the user moves the divider. (This property is false by default—you just see a line showing

the proposed divider location while you move the divider.)

public JSplitPane(int orientation, Component leftOrTop, Component bottomOrRight)

public JSplitPane(int orientation, boolean continuousLayout, Component leftOrTop, Component bottomOrRight)

These constructors allow you to pick your orientation and the initial components for each pane. Depending

on the orientation you choose, the first component is placed in the left or top pane, and the second

component fills the other pane. If you give a true value as thecontinuousLayout argument to the second

constructor, both panes are repainted continuously as the user moves the divider.



11.1.4 Control Methods



public void remove(Component comp)

public void remove(int index)

public void removeAll( )

Remove components from the split pane. Typically, you use the first of these methods to remove one

component at a time.



public void resetToPreferredSizes( )

Reset the sizes of the components to their preferred sizes. The preferred size of a component is

determined by the UI manager for the split pane. The preferred size of a split pane is the sum of the

preferred sizes of its children (including the divider).

public void setDividerLocation(double position)

This convenience method does the pixel calculating for you so that you can specify a position for the

divider. The position you give is the fraction of the whole pane given to the left of the pane (for a horizontal



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



.



split) or the top of the pane (for a vertical split). For example, with a horizontal split, a value of 0.75 assigns

75% of the pane to the component on the left. The position must be a value between 0 and 1. If it isn't, you

get an IllegalArgumentException.



11.1.5 Minimum and Preferred Sizes

When setting up your split panes, watch out for the minimum and preferred sizes of the two components. If you look

back at the code for Figure 11-2, you can see we forcibly set the minimum sizes of the two text areas. The

boundaries observed by the divider in a split pane are dictated by the minimum sizes of the two components. Some

components, such as JTextArea , define their minimum size as the size they are initially shown with. That often

works fine, but in the case of the split pane, it means that you cannot adjust the division between the two text areas

(as both are already at their minimum sizes). The same is true for containers such as panels or the JScrollPane we

discuss in the next section.

You should also set the preferred size of the first component if you want the split pane to come up correctly the first

time. In the previous example, if you remove the line that sets the preferred size of jt1, then jt1 comes up with room

for one row of text, and jt2 takes everything else. Of course, you could also set thedividerLocation property before

making the split pane visible. (Note that if you are using an older version of the JDK—such as 1.2.2—you have to set

the preferred size.)

I l@ve RuBoard



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



I l@ve RuBoard



11.2 The JScrollPane Class

The JScrollPane



class offers a more flexible version of theScrollPane class found in the AWT package. Beyond



the automatic scrollbars, you can put in horizontal and vertical



headers as well as active components in the



corners of your pane. (Figure 11-6 shows the exact areas available in aJScrollPane, which is managed by the



ScrollPaneLayout class.)

Many Swing components use JScrollPane to handle their scrolling. TheJList component, for example, does not

handle scrolling on its own. Instead, it concentrates on presenting the list and making selection easy, assuming you'll

put it inside a JScrollPane if you need scrolling. Figure 11-3 shows a simpleJScrollPane in action with aJList

object.



Figure 11-3. JScrollPane showing two portions of a list that is too long for one screen



This particular example does not take advantage of the row or column headers. The scrollpane adds the scrollbars

automatically, but only "as needed." If we were to resize the window to make it much larger, the scrollbars would

become inactive. Here's the code that builds this pane:



// ScrollList.java

// A simple JScrollPane

//

import javax.swing.*;

import java.awt.*;

public class ScrollList extends JFrame {



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



.



JScrollPane scrollpane;

public ScrollList( ) {

super("JScrollPane Demonstration");

setSize(300, 200);

setDefaultCloseOperation(EXIT_ON_CLOSE);

String categories[] = { "Household", "Office", "Extended Family",

"Company (US)", "Company (World)", "Team",

"Will", "Birthday Card List", "High School",

"Country", "Continent", "Planet" };

JList list = new JList(categories);

scrollpane = new JScrollPane(list);

getContentPane( ).add(scrollpane, BorderLayout.CENTER);

}

public static void main(String args[]) {

ScrollList sl = new ScrollList( );

sl.setVisible(true);

}

}

A similar technique can be used with many of the Swing components, including JPanel , JTree, JTable, and



JTextArea . Chapter 15 discusses the JTable class and its particular use ofJScrollPane.

While you will certainly use JScrollPane with many of the Swing components, you can also build your own

components and drop them into a scrollable area. You may bundle up a piece of your user interface into one panel

and make that panel scrollable.

Here's a short example that takes the items from our previous list and turns them into a basic census form. As you

can see in Figure 11-4, the form itself is a panel with a size of 600 x 400 pixels. We display it insideJScrollPane

a

and

make the application 300 x 200.



Figure 11-4. A JScrollPane with a component larger than the application window



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



The only change from our first program is that we now have to build the census panel from scratch. We build a



JPanel containing various labels and radio buttons, and slap it into JScrollPane

a

. The only logic involved is figuring

out whether we're adding a label or a button, and getting the buttons into appropriate ButtonGroups (one group per

row).



// ScrollDemo.java

// A simple JScrollPane demonstration

//

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class ScrollDemo extends JFrame {

JScrollPane scrollpane;

public ScrollDemo( ) {

super("JScrollPane Demonstration");

setSize(300, 200);

setDefaultCloseOperation(EXIT_ON_CLOSE);

init( );

setVisible(true);

}

public void init( ) {

JRadioButton form[][] = new JRadioButton[12][5];

String counts[] = { "", "0-1", "2-5", "6-10", "11-100", "101+" };

String categories[] = { "Household", "Office", "Extended Family",

"Company (US)", "Company (World)", "Team",

"Will", "Birthday Card List", "High School",

"Country", "Continent", "Planet" };

JPanel p = new JPanel( );

p.setSize(600, 400);

p.setLayout(new GridLayout(13, 6, 10, 0));

for (int row = 0; row < 13; row++) {

ButtonGroup bg = new ButtonGroup( );

for (int col = 0; col < 6; col++) {

if (row == 0) {

p.add(new JLabel(counts[col]));

}

else {

if (col == 0) {

p.add(new JLabel(categories[row - 1]));



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



}

else {

form[row - 1][col - 1] = new JRadioButton( );

bg.add(form[row -1][col - 1]);

p.add(form[row -1][col - 1]);

}

}

}

}

scrollpane = new JScrollPane(p);

getContentPane( ).add(scrollpane, BorderLayout.CENTER);

}

public static void main(String args[]) {

new ScrollDemo( );

}

}



11.2.1 Properties

Table 11-3 shows how theJScrollPane properties grant you access to the five main components (not the corners)

and the scrollbar policies. The valid values for horizontalScrollBarPolicy and verticalScrollBarPolicy are

defined in the ScrollPaneConstants interface (see Table 11-8). The validateRoot property is alwaystrue to

ensure that revalidation calls to any of the pane's descendants cause the scrollpane and all of its descendants to be

validated, and that revalidation doesn't go any further than the JScrollPane, which would be redundant. The



wheelScrollingEnabled property, added in SDK 1.4, allows you to enable or disable support for mice with a

middle-wheel button.



Table 11-3. JScrollPane properties

Property

accessibleContext

columnHeader



Data type



o



b



columnHeaderView

componentOrientation



b, o



b

b



horizontalScrollBarPolicy

b, o



opaque

rowHeader



JScrollPane.AccessibleJScrollPane( )



JViewport



null



·

·



int



·



JScrollBar



·



int



·



·



HORIZONTAL_SCROLLBAR_AS_NEEDED



LayoutManager



·



·



new ScrollPaneLayout( )



boolean

b



Default value



AccessibleContext ·



Component



horizontalScrollBar



layout



get is set



JViewport



·



null



·

·



ComponentOrientation.UNKNOWN



false

null



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



rowHeaderView



Component



UI



ScrollPane-UI

o



UIClassID



String



validateRoot



boolean

b



·

·



·

·



int



·



JViewport



·



Border



·



viewportBorderBounds



Rectangle



·



viewportView



Component



b



verticalScrollBarPolicy

viewport



b



viewportBorder



b



b 1.4



boolean



wheelScrollingEnabled ,

1.4



b



·



From L&F

"ScrollPaneUI"



JScrollBar



verticalScrollbar



.



true

null

·



VERTICAL_SCROLLBAR_AS_NEEDED

null



·



null



·

·



·



true



o



since 1.4, bound, overridden



See also properties from the



JComponent class (Table 3-6).



Given that you already have a viewport set up for the row and column headers, or the main viewport itself, you can

use the columnHeaderView



, rowHeaderView, andviewportView properties to modify the contents of these



viewports. Note that the set accessors for these properties don't create new viewport objects; they simply set the

view to display the given component.



11.2.2 Constructors

public JScrollPane( )

public JScrollPane(Component view)

public JScrollPane(Component view, int verticalScrollBarPolicy, int horizontalScrollBarPolicy)

public JScrollPane(int verticalScrollBarPolicy, int horizontalScrollBarPolicy)

Create new scrollpanes. You can start off by specifying the view (i.e., the component to scroll), the scrollbar

policies, or both. Just make sure you get the scrollbar policies in the right order! Of course, any of these

pieces can be specified or changed after the scrollpane has been created. See the setViewportView( )

method later in this chapter.



11.2.3 Pane Component Methods



public JScrollBar createHorizontalScrollBar( )



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 11. Specialty Panes and Layout Managers

Tải bản đầy đủ ngay(0 tr)

×