Java/Swing JFC/Splitpane
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 A quick test of the JSplitPane class
- 2 Continuously move the divider and resize its child components while the user is dragging the divider
- 3 Create a left-right split pane
- 4 Create a top-bottom split pane
- 5 Distributing Space When a JSplitPane Container Is Resized
- 6 Getting and Setting the Divider Location in a JSplitPane Container
- 7 Getting the Setting the Children in a JSplitPane Container
- 8 Property Split
- 9 Resize SplitPane
- 10 SplitPane Demo 2
- 11 SplitPane Sample 3
- 12 SplitPane: VerticalSplit
- 13 Swing SplitPane Sample
- 14 The split pane supports a one-touch-expandable capability that allows the user to conveniently move the divider to either end with a single click
- 15 Use the split pane
A quick test of the JSplitPane class
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly
*/
// SimpleSplitPane.java
//A quick test of the JSplitPane class.
//
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
public class SimpleSplitPane extends JFrame {
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);
}
}
Continuously move the divider and resize its child components while the user is dragging the divider
import javax.swing.JButton;
import javax.swing.JSplitPane;
public class Main {
public static void main(String[] argv) throws Exception {
JButton topComponent = new JButton("top");
JButton bottomComponent = new JButton("bottom");
JSplitPane vpane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topComponent, bottomComponent);
boolean b = vpane.isContinuousLayout(); // false by default
// Set the split pane to continuously resize the child components which the divider is dragged
vpane.setContinuousLayout(true);
}
}
Create a left-right split pane
import javax.swing.JButton;
import javax.swing.JSplitPane;
public class Main {
public static void main(String[] argv) throws Exception {
JButton leftComponent = new JButton("left");
JButton rightComponent = new JButton("right");
// Create a left-right split pane
JSplitPane hpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, rightComponent);
}
}
Create a top-bottom split pane
import javax.swing.JButton;
import javax.swing.JSplitPane;
public class Main {
public static void main(String[] argv) throws Exception {
JButton topComponent = new JButton("top");
JButton bottomComponent = new JButton("bottom");
JSplitPane vpane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topComponent, bottomComponent);
}
}
Distributing Space When a JSplitPane Container Is Resized
import javax.swing.JButton;
import javax.swing.JSplitPane;
public class Main {
public static void main(String[] argv) throws Exception {
JButton leftComponent = new JButton("left");
JButton rightComponent = new JButton("right");
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, rightComponent);
double weight = pane.getResizeWeight(); // 0.0 by default
weight = 1D;
pane.setResizeWeight(weight);
weight = .5D;
pane.setResizeWeight(weight);
}
}
Getting and Setting the Divider Location in a JSplitPane Container
import javax.swing.JButton;
import javax.swing.JSplitPane;
public class Main {
public static void main(String[] argv) throws Exception {
JButton leftComponent = new JButton("left");
JButton rightComponent = new JButton("right");
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, rightComponent);
int loc = pane.getDividerLocation();
loc = (int) ((pane.getBounds().getWidth() - pane.getDividerSize()) / 2);
pane.setDividerLocation(loc);
double propLoc = .5D;
pane.setDividerLocation(propLoc);
}
}
Getting the Setting the Children in a JSplitPane Container
import javax.swing.JButton;
import javax.swing.JSplitPane;
public class Main {
public static void main(String[] argv) throws Exception {
JButton leftComponent = new JButton("left");
JButton rightComponent = new JButton("right");
JButton topComponent = new JButton("top");
JButton bottomComponent = new JButton("bottom");
JSplitPane hpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, rightComponent);
JSplitPane vpane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topComponent, bottomComponent);
leftComponent = (JButton) hpane.getLeftComponent();
rightComponent = (JButton) hpane.getRightComponent();
topComponent = (JButton) vpane.getTopComponent();
bottomComponent = (JButton) vpane.getBottomComponent();
hpane.setLeftComponent(topComponent);
hpane.setRightComponent(bottomComponent);
vpane.setTopComponent(leftComponent);
vpane.setBottomComponent(rightComponent);
}
}
Property Split
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
public class PropertySplit {
public static void main(String args[]) {
JFrame frame = new JFrame("Property Split");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPane.setContinuousLayout(true);
splitPane.setOneTouchExpandable(true);
JComponent topComponent = new OvalPanel();
splitPane.setTopComponent(topComponent);
JComponent bottomComponent = new OvalPanel();
splitPane.setBottomComponent(bottomComponent);
PropertyChangeListener propertyChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent changeEvent) {
JSplitPane sourceSplitPane = (JSplitPane) changeEvent
.getSource();
String propertyName = changeEvent.getPropertyName();
if (propertyName
.equals(JSplitPane.LAST_DIVIDER_LOCATION_PROPERTY)) {
int current = sourceSplitPane.getDividerLocation();
System.out.println("Current: " + current);
Integer last = (Integer) changeEvent.getNewValue();
System.out.println("Last: " + last);
Integer priorLast = (Integer) changeEvent.getOldValue();
System.out.println("Prior last: " + priorLast);
}
}
};
splitPane.addPropertyChangeListener(propertyChangeListener);
Container contentPane = frame.getContentPane();
contentPane.add(splitPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
class OvalPanel extends JPanel {
Color color;
public OvalPanel() {
this(Color.black);
}
public OvalPanel(Color color) {
this.color = color;
}
public void paintComponent(Graphics g) {
int width = getWidth();
int height = getHeight();
g.setColor(color);
g.drawOval(0, 0, width, height);
}
}
Resize SplitPane
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
public class ResizeSplit {
public static void main(String args[]) {
String title = "Resize Split";
final JFrame vFrame = new JFrame(title);
vFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton topButton = new JButton("Top");
JButton bottomButton = new JButton("Bottom");
final JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPane.setTopComponent(topButton);
splitPane.setBottomComponent(bottomButton);
ActionListener oneActionListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
splitPane.setResizeWeight(1.0);
vFrame.setSize(300, 250);
vFrame.validate();
}
};
bottomButton.addActionListener(oneActionListener);
ActionListener anotherActionListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
splitPane.setResizeWeight(0.5);
vFrame.setSize(300, 250);
vFrame.validate();
}
};
topButton.addActionListener(anotherActionListener);
vFrame.getContentPane().add(splitPane, BorderLayout.CENTER);
vFrame.setSize(300, 150);
vFrame.setVisible(true);
}
}
SplitPane Demo 2
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import java.awt.Dimension;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class SplitPaneDemo2 extends JFrame implements ListSelectionListener {
private JLabel label;
public SplitPaneDemo2() {
super("SplitPaneDemo2");
//Create an instance of SplitPaneDemo
SplitPaneDemo splitPaneDemo = new SplitPaneDemo();
JSplitPane top = splitPaneDemo.getSplitPane();
splitPaneDemo.getImageList().addListSelectionListener(this);
//XXXX: Bug #4131528, borders on nested split panes accumulate.
//Workaround: Set the border on any split pane within
//another split pane to null. Components within nested split
//panes need to have their own border for this to work well.
top.setBorder(null);
//Create a regular old label
label = new JLabel("Click on an image name in the list.", JLabel.CENTER);
//Create a split pane and put "top" (a split pane)
//and JLabel instance in it.
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, top,
label);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(180);
//Provide minimum sizes for the two components in the split pane
top.setMinimumSize(new Dimension(100, 50));
label.setMinimumSize(new Dimension(100, 30));
//Add the split pane to this frame
getContentPane().add(splitPane);
}
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
JList theList = (JList) e.getSource();
if (theList.isSelectionEmpty()) {
label.setText("Nothing selected.");
} else {
int index = theList.getSelectedIndex();
label.setText("Selected image number " + index);
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new SplitPaneDemo2();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application"s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
class SplitPaneDemo implements ListSelectionListener {
private Vector imageNames;
private JLabel picture;
private JList list;
private JSplitPane splitPane;
public SplitPaneDemo() {
//Read image names from a properties file.
ResourceBundle imageResource;
try {
imageResource = ResourceBundle.getBundle("imagenames");
String imageNamesString = imageResource.getString("images");
imageNames = parseList(imageNamesString);
} catch (MissingResourceException e) {
handleMissingResource(e);
}
//Create the list of images and put it in a scroll pane.
list = new JList(imageNames);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setSelectedIndex(0);
list.addListSelectionListener(this);
JScrollPane listScrollPane = new JScrollPane(list);
//Set up the picture label and put it in a scroll pane.
ImageIcon firstImage = createImageIcon("images/"
+ (String) imageNames.firstElement());
if (firstImage != null) {
picture = new JLabel(firstImage);
} else {
picture = new JLabel((String) imageNames.firstElement());
}
JScrollPane pictureScrollPane = new JScrollPane(picture);
//Create a split pane with the two scroll panes in it.
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listScrollPane,
pictureScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(150);
//Provide minimum sizes for the two components in the split pane.
Dimension minimumSize = new Dimension(100, 50);
listScrollPane.setMinimumSize(minimumSize);
pictureScrollPane.setMinimumSize(minimumSize);
//Provide a preferred size for the split pane.
splitPane.setPreferredSize(new Dimension(400, 200));
}
//Used by SplitPaneDemo2
public JList getImageList() {
return list;
}
public JSplitPane getSplitPane() {
return splitPane;
}
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
JList theList = (JList) e.getSource();
if (theList.isSelectionEmpty()) {
picture.setIcon(null);
picture.setText(null);
} else {
int index = theList.getSelectedIndex();
ImageIcon newImage = createImageIcon("images/"
+ (String) imageNames.elementAt(index));
picture.setIcon(newImage);
if (newImage != null) {
picture.setText(null);
} else {
picture.setText("Image not found: "
+ (String) imageNames.elementAt(index));
}
}
}
protected static Vector parseList(String theStringList) {
Vector v = new Vector(10);
StringTokenizer tokenizer = new StringTokenizer(theStringList, " ");
while (tokenizer.hasMoreTokens()) {
String image = tokenizer.nextToken();
v.addElement(image);
}
return v;
}
/** Called when the image property file can"t be found. */
private void handleMissingResource(MissingResourceException e) {
System.err.println();
System.err.println("Can"t find the properties file "
+ "that contains the image names.");
System.err.println("Its name should be imagenames.properties, "
+ "and it should");
System.err.println("contain a single line that specifies "
+ "one or more image");
System.err.println("files to be found in a directory "
+ "named images. Example:");
System.err.println();
System.err.println(" images=Bird.gif Cat.gif Dog.gif");
System.err.println();
throw (e); //Used to be exit(1), but that causes the console to
//go away under Java Web Start; this way, you"re
//more likely to see a relevant error message.
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = SplitPaneDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn"t find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("SplitPaneDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SplitPaneDemo splitPaneDemo = new SplitPaneDemo();
frame.getContentPane().add(splitPaneDemo.getSplitPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application"s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
SplitPane Sample 3
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
public class SplitPaneSample {
public static void main(String args[]) {
JFrame vFrame = new JFrame("JSplitPane Sample");
vFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSplitPane vSplitPane = new JSplitPane();
vSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
vFrame.getContentPane().add(vSplitPane, BorderLayout.CENTER);
vFrame.setSize(300, 150);
vFrame.setVisible(true);
JFrame hFrame = new JFrame("JSplitPane Sample");
JSplitPane hSplitPane = new JSplitPane();
hFrame.getContentPane().add(hSplitPane, BorderLayout.CENTER);
hFrame.setSize(300, 150);
hFrame.setVisible(true);
}
}
SplitPane: VerticalSplit
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
public class VerticalSplit {
public static void main(String args[]) {
JFrame vFrame = new JFrame("Vertical Split");
vFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent leftButton = new JButton("Left");
JComponent rightButton = new JButton("Right");
final JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPane.setOneTouchExpandable(true);
splitPane.setLeftComponent(leftButton);
splitPane.setRightComponent(rightButton);
ActionListener oneActionListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
splitPane.resetToPreferredSizes();
}
};
((JButton) rightButton).addActionListener(oneActionListener);
ActionListener anotherActionListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
splitPane.setDividerLocation(10);
splitPane.setContinuousLayout(true);
}
};
((JButton) leftButton).addActionListener(anotherActionListener);
vFrame.getContentPane().add(splitPane, BorderLayout.CENTER);
vFrame.setSize(300, 150);
vFrame.setVisible(true);
}
}
Swing SplitPane Sample
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
public class SwingSplitSample {
public static void main(String args[]) {
JFrame frame = new JFrame("JSplitPane Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSplitPane splitPane = new JSplitPane();
splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
frame.getContentPane().add(splitPane, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
The split pane supports a one-touch-expandable capability that allows the user to conveniently move the divider to either end with a single click
import javax.swing.JButton;
import javax.swing.JSplitPane;
public class Main {
public static void main(String[] argv) throws Exception {
JButton topComponent = new JButton("top");
JButton bottomComponent = new JButton("bottom");
JSplitPane vpane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topComponent, bottomComponent);
boolean b = vpane.isOneTouchExpandable(); // false by default
vpane.setOneTouchExpandable(true);
}
}
Use the split pane
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
public class SplitSample extends JFrame {
protected JSplitPane split;
public SplitSample() {
super("Simple Split Pane");
setSize(400, 400);
getContentPane().setLayout(new BorderLayout());
JSplitPane spLeft = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JPanel(), new JPanel());
spLeft.setDividerSize(8);
spLeft.setContinuousLayout(true);
JSplitPane spRight = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JPanel(), new JPanel());
spRight.setDividerSize(8);
spRight.setContinuousLayout(true);
split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, spLeft, spRight);
split.setContinuousLayout(false);
split.setOneTouchExpandable(true);
getContentPane().add(split, BorderLayout.CENTER);
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
setVisible(true);
}
public static void main(String argv[]) {
new SplitSample();
}
}