Java/Swing JFC/ScrollBar
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 Accessible Scroll Demo
- 2 Always display scrollbar
- 3 A quick demonstration of JScrollBar both vertical and horizontal
- 4 Expandable SplitPane
- 5 Get the default scrollbar policy
- 6 How to use scrollbar and react to its action
- 7 JScrollBar and Adjustment event
- 8 JScrollPane: Button Corner Sample
- 9 JScrollPane Corner
- 10 JScrollPane to hold scrollable component
- 11 Listening for Scrollbar Value Changes in a JScrollPane Container
- 12 Make the scrollbars always appear
- 13 Make the scrollbars never appear
- 14 ScrollBar Pieces
- 15 Use Adjustment Events in Swing
Accessible Scroll Demo
/* 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.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Locale;
import javax.accessibility.Accessible;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRole;
import javax.accessibility.AccessibleState;
import javax.accessibility.AccessibleStateSet;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToggleButton;
import javax.swing.Scrollable;
import javax.swing.SwingConstants;
public class AccessibleScrollDemo extends JPanel {
private Rule columnView;
private Rule rowView;
private JToggleButton isMetric;
private ScrollablePicture picture;
public AccessibleScrollDemo() {
//Load the photograph into an image icon.
ImageIcon david = new ImageIcon("images/youngdad.jpeg");
david.setDescription("Photograph of David McNabb in his youth.");
//Create the row and column headers
columnView = new Rule(Rule.HORIZONTAL, true);
columnView.setPreferredWidth(david.getIconWidth());
columnView.getAccessibleContext().setAccessibleName("Column Header");
columnView.getAccessibleContext().setAccessibleDescription(
"Displays horizontal ruler for "
+ "measuring scroll pane client.");
rowView = new Rule(Rule.VERTICAL, true);
rowView.setPreferredHeight(david.getIconHeight());
rowView.getAccessibleContext().setAccessibleName("Row Header");
rowView.getAccessibleContext().setAccessibleDescription(
"Displays vertical ruler for "
+ "measuring scroll pane client.");
//Create the corners
JPanel buttonCorner = new JPanel();
isMetric = new JToggleButton("cm", true);
isMetric.setFont(new Font("SansSerif", Font.PLAIN, 11));
isMetric.setMargin(new Insets(2, 2, 2, 2));
isMetric.addItemListener(new UnitsListener());
isMetric.setToolTipText("Toggles rulers" unit of measure "
+ "between inches and centimeters.");
buttonCorner.add(isMetric); //Use the default FlowLayout
buttonCorner.getAccessibleContext().setAccessibleName(
"Upper Left Corner");
String desc = "Fills the corner of a scroll pane "
+ "with color for aesthetic reasons.";
Corner lowerLeft = new Corner();
lowerLeft.getAccessibleContext().setAccessibleName("Lower Left Corner");
lowerLeft.getAccessibleContext().setAccessibleDescription(desc);
Corner upperRight = new Corner();
upperRight.getAccessibleContext().setAccessibleName(
"Upper Right Corner");
upperRight.getAccessibleContext().setAccessibleDescription(desc);
//Set up the scroll pane
picture = new ScrollablePicture(david, columnView.getIncrement());
picture.setToolTipText(david.getDescription());
picture.getAccessibleContext().setAccessibleName("Scroll pane client");
JScrollPane pictureScrollPane = new JScrollPane(picture);
pictureScrollPane.setPreferredSize(new Dimension(300, 250));
pictureScrollPane.setViewportBorder(BorderFactory
.createLineBorder(Color.black));
pictureScrollPane.setColumnHeaderView(columnView);
pictureScrollPane.setRowHeaderView(rowView);
pictureScrollPane
.setCorner(JScrollPane.UPPER_LEFT_CORNER, buttonCorner);
pictureScrollPane.setCorner(JScrollPane.LOWER_LEFT_CORNER, lowerLeft);
pictureScrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER, upperRight);
//Put it in this panel
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(pictureScrollPane);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
class UnitsListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
//turn it to metric
rowView.setIsMetric(true);
columnView.setIsMetric(true);
} else {
//turn it to inches
rowView.setIsMetric(false);
columnView.setIsMetric(false);
}
picture.setMaxUnitIncrement(rowView.getIncrement());
}
}
public static void main(String s[]) {
JFrame frame = new JFrame("AccessibleScrollDemo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setContentPane(new AccessibleScrollDemo());
frame.pack();
frame.setVisible(true);
}
}
class Rule extends JComponent implements Accessible {
public static final int INCH = Toolkit.getDefaultToolkit()
.getScreenResolution();
public static final int HORIZONTAL = 0;
public static final int VERTICAL = 1;
public static final int SIZE = 35;
public int orientation;
public boolean isMetric;
private int increment;
private int units;
public Rule(int o, boolean m) {
orientation = o;
isMetric = m;
setIncrementAndUnits();
}
public void setIsMetric(boolean isMetric) {
if (accessibleContext != null && this.isMetric != isMetric) {
if (isMetric) {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleRulerState.INCHES,
AccessibleRulerState.CENTIMETERS);
} else {
accessibleContext.firePropertyChange(
AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleRulerState.CENTIMETERS,
AccessibleRulerState.INCHES);
}
}
this.isMetric = isMetric;
setIncrementAndUnits();
repaint();
}
private void setIncrementAndUnits() {
if (isMetric) {
units = (int) ((double) INCH / (double) 2.54); // dots per
// centimeter
increment = units;
} else {
units = INCH;
increment = units / 2;
}
}
public boolean isMetric() {
return this.isMetric;
}
public int getIncrement() {
return increment;
}
public void setPreferredHeight(int ph) {
setPreferredSize(new Dimension(SIZE, ph));
}
public void setPreferredWidth(int pw) {
setPreferredSize(new Dimension(pw, SIZE));
}
public void paintComponent(Graphics g) {
Rectangle drawHere = g.getClipBounds();
// Fill clipping area with dirty brown/orange.
g.setColor(new Color(230, 163, 4));
g.fillRect(drawHere.x, drawHere.y, drawHere.width, drawHere.height);
// Do the ruler labels in a small font that"s black.
g.setFont(new Font("SansSerif", Font.PLAIN, 10));
g.setColor(Color.black);
// Some vars we need.
int end = 0;
int start = 0;
int tickLength = 0;
String text = null;
// Use clipping bounds to calculate first tick
// and last tick location.
if (orientation == HORIZONTAL) {
start = (drawHere.x / increment) * increment;
end = (((drawHere.x + drawHere.width) / increment) + 1) * increment;
} else {
start = (drawHere.y / increment) * increment;
end = (((drawHere.y + drawHere.height) / increment) + 1)
* increment;
}
// Make a special case of 0 to display the number
// within the rule and draw a units label.
if (start == 0) {
text = Integer.toString(0) + (isMetric ? " cm" : " in");
tickLength = 10;
if (orientation == HORIZONTAL) {
g.drawLine(0, SIZE - 1, 0, SIZE - tickLength - 1);
g.drawString(text, 2, 21);
} else {
g.drawLine(SIZE - 1, 0, SIZE - tickLength - 1, 0);
g.drawString(text, 9, 10);
}
text = null;
start = increment;
}
// ticks and labels
for (int i = start; i < end; i += increment) {
if (i % units == 0) {
tickLength = 10;
text = Integer.toString(i / units);
} else {
tickLength = 7;
text = null;
}
if (tickLength != 0) {
if (orientation == HORIZONTAL) {
g.drawLine(i, SIZE - 1, i, SIZE - tickLength - 1);
if (text != null)
g.drawString(text, i - 3, 21);
} else {
g.drawLine(SIZE - 1, i, SIZE - tickLength - 1, i);
if (text != null)
g.drawString(text, 9, i + 3);
}
}
}
}
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleRuler();
}
return accessibleContext;
}
protected class AccessibleRuler extends AccessibleJComponent {
public AccessibleRole getAccessibleRole() {
return AccessibleRuleRole.RULER;
}
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
if (orientation == VERTICAL) {
states.add(AccessibleState.VERTICAL);
} else {
states.add(AccessibleState.HORIZONTAL);
}
if (isMetric) {
states.add(AccessibleRulerState.CENTIMETERS);
} else {
states.add(AccessibleRulerState.INCHES);
}
return states;
}
}
}
class AccessibleRuleRole extends AccessibleRole {
public static final AccessibleRuleRole RULER = new AccessibleRuleRole(
"ruler");
protected AccessibleRuleRole(String key) {
super(key);
}
//Should really provide localizable versions of these names.
public String toDisplayString(String resourceBundleName, Locale locale) {
return key;
}
}
class AccessibleRulerState extends AccessibleState {
public static final AccessibleRulerState INCHES = new AccessibleRulerState(
"inches");
public static final AccessibleRulerState CENTIMETERS = new AccessibleRulerState(
"centimeters");
protected AccessibleRulerState(String key) {
super(key);
}
//Should really provide localizable versions of these names.
public String toDisplayString(String resourceBundleName, Locale locale) {
return key;
}
}
class ScrollablePicture extends JLabel implements Scrollable {
private int maxUnitIncrement = 1;
public ScrollablePicture(ImageIcon i, int m) {
super(i);
maxUnitIncrement = m;
}
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
public int getScrollableUnitIncrement(Rectangle visibleRect,
int orientation, int direction) {
int currentPosition = 0;
if (orientation == SwingConstants.HORIZONTAL)
currentPosition = visibleRect.x;
else
currentPosition = visibleRect.y;
if (direction < 0) {
int newPosition = currentPosition
- (currentPosition / maxUnitIncrement) * maxUnitIncrement;
return (newPosition == 0) ? maxUnitIncrement : newPosition;
} else {
return ((currentPosition / maxUnitIncrement) + 1)
* maxUnitIncrement - currentPosition;
}
}
public int getScrollableBlockIncrement(Rectangle visibleRect,
int orientation, int direction) {
if (orientation == SwingConstants.HORIZONTAL)
return visibleRect.width - maxUnitIncrement;
else
return visibleRect.height - maxUnitIncrement;
}
public boolean getScrollableTracksViewportWidth() {
return false;
}
public boolean getScrollableTracksViewportHeight() {
return false;
}
public void setMaxUnitIncrement(int pixels) {
maxUnitIncrement = pixels;
}
}
class Corner extends JComponent implements Accessible {
public void paintComponent(Graphics g) {
// Fill me with dirty brown/orange.
g.setColor(new Color(230, 163, 4));
g.fillRect(0, 0, getWidth(), getHeight());
}
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleCorner();
}
return accessibleContext;
}
protected class AccessibleCorner extends AccessibleJComponent {
//Inherit everything, override nothing.
}
}
Always display scrollbar
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.WindowConstants;
public class Main extends JFrame {
JTextArea textArea;
public Main() {
super();
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container contentPane = this.getContentPane();
textArea = new JTextArea();
JScrollPane pane = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
contentPane.add(pane, BorderLayout.CENTER);
}
public static void main(String[] args) {
JFrame f = new Main();
f.setSize(300, 200);
f.setVisible(true);
}
}
A quick demonstration of JScrollBar both vertical and horizontal
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly
*/
// SwingScrollBarExample.java
// A quick demonstration of JScrollBar (both vertical and horizontal).
//
import java.awt.BorderLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
public class SwingScrollBarExample extends JPanel {
JLabel label;
public SwingScrollBarExample() {
super(true);
label = new JLabel();
setLayout(new BorderLayout());
JScrollBar hbar = new JScrollBar(JScrollBar.HORIZONTAL, 30, 20, 0, 300);
JScrollBar vbar = new JScrollBar(JScrollBar.VERTICAL, 30, 40, 0, 300);
hbar.setUnitIncrement(2);
hbar.setBlockIncrement(1);
hbar.addAdjustmentListener(new MyAdjustmentListener());
vbar.addAdjustmentListener(new MyAdjustmentListener());
add(hbar, BorderLayout.SOUTH);
add(vbar, BorderLayout.EAST);
add(label, BorderLayout.CENTER);
}
class MyAdjustmentListener implements AdjustmentListener {
public void adjustmentValueChanged(AdjustmentEvent e) {
label.setText(" New Value is " + e.getValue() + " ");
repaint();
}
}
public static void main(String s[]) {
JFrame frame = new JFrame("Scroll Bar Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new SwingScrollBarExample());
frame.setSize(200, 200);
frame.setVisible(true);
}
}
Expandable SplitPane
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 ExpandableSplit {
public static void main(String args[]) {
String title = (args.length == 0 ? "Expandable Split" : args[0]);
JFrame vFrame = new JFrame(title);
vFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent leftButton = new JButton("Top");
JComponent rightButton = new JButton("Bottom");
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);
}
}
Get the default scrollbar policy
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Main {
public static void main(String[] argv) throws Exception {
JTextArea textArea = new JTextArea();
JScrollPane pane = new JScrollPane(textArea);
// Get the default scrollbar policy
int hpolicy = pane.getHorizontalScrollBarPolicy();
// JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED;
int vpolicy = pane.getVerticalScrollBarPolicy();
// JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED;
}
}
How to use scrollbar and react to its action
import java.awt.Adjustable;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
public class ScrollBarColorSelect extends JFrame implements AdjustmentListener {
private JLabel redLabel;
private JLabel greenLabel;
private JLabel blueLabel;
private JScrollBar red;
private JScrollBar green;
private JScrollBar blue;
private JPanel colorPanel;
public ScrollBarColorSelect() {
setTitle("ColorSelect");
setSize(300, 200);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container contentPane = getContentPane();
JPanel p = new JPanel();
p.setLayout(new GridLayout(3, 2,3,3));
p.add(redLabel = new JLabel("Red 0"));
p.add(red = new JScrollBar(Adjustable.HORIZONTAL, 0, 0, 0, 255));
red.setBlockIncrement(16);
red.addAdjustmentListener(this);
p.add(greenLabel = new JLabel("Green 0"));
p.add(green = new JScrollBar(Adjustable.HORIZONTAL, 0, 0, 0, 255));
green.setBlockIncrement(16);
green.addAdjustmentListener(this);
p.add(blueLabel = new JLabel("Blue 0"));
p.add(blue = new JScrollBar(Adjustable.HORIZONTAL, 0, 0, 0, 255));
blue.setBlockIncrement(16);
blue.addAdjustmentListener(this);
contentPane.add(p, "South");
colorPanel = new JPanel();
colorPanel.setBackground(new Color(0, 0, 0));
contentPane.add(colorPanel, "Center");
}
public void adjustmentValueChanged(AdjustmentEvent evt) {
redLabel.setText("Red " + red.getValue());
greenLabel.setText("Green " + green.getValue());
blueLabel.setText("Blue " + blue.getValue());
colorPanel.setBackground(new Color(red.getValue(), green.getValue(),
blue.getValue()));
colorPanel.repaint();
}
public static void main(String[] args) {
JFrame f = new ScrollBarColorSelect();
f.show();
}
}
JScrollBar and Adjustment event
import java.awt.Adjustable;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.JFrame;
import javax.swing.JScrollBar;
public class Main {
JScrollBar scrollBarVertical = new JScrollBar();
JScrollBar scrollbarHorizontal = new JScrollBar(Adjustable.HORIZONTAL);
Main() {
JFrame f = new JFrame();
f.setLayout(new FlowLayout());
f.setSize(280, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scrollBarVertical.setPreferredSize(new Dimension(20, 200));
scrollbarHorizontal.setPreferredSize(new Dimension(200, 20));
scrollbarHorizontal.setValue(50);
scrollBarVertical.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent ae) {
if (scrollBarVertical.getValueIsAdjusting())
return;
System.out.println("Value of vertical scroll bar: " + ae.getValue());
}
});
scrollbarHorizontal.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent ae) {
System.out.println("Value of horizontal scroll bar: " + ae.getValue());
}
});
f.add(scrollBarVertical);
f.add(scrollbarHorizontal);
f.setVisible(true);
}
public static void main(String args[]) {
new Main();
}
}
JScrollPane: Button Corner Sample
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
public class ButtonCornerSample {
public static void main(String args[]) {
JFrame frame = new JFrame("Cornering Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Icon acrossLogo = new ImageIcon("logo-across.jpg");
Icon downLogo = new ImageIcon("logo-down.jpg");
Icon bookCover = new ImageIcon("puzzlebook.jpg");
JLabel columnLabel = new JLabel(acrossLogo);
JLabel rowLabel = new JLabel(downLogo);
JLabel coverLabel = new JLabel(bookCover);
JButton button = new JButton("+");
button.setFont(new Font("Monospaced", Font.PLAIN, 8));
JScrollPane scrollPane = new JScrollPane(coverLabel);
scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, button);
scrollPane.setColumnHeaderView(columnLabel);
scrollPane.setRowHeaderView(rowLabel);
ActionListener actionListener = new JScrollPaneToTopAction(scrollPane);
button.addActionListener(actionListener);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
class JScrollPaneToTopAction implements ActionListener {
JScrollPane scrollPane;
public JScrollPaneToTopAction(JScrollPane scrollPane) {
if (scrollPane == null) {
throw new IllegalArgumentException(
"JScrollPaneToTopAction: null JScrollPane");
}
this.scrollPane = scrollPane;
}
public void actionPerformed(ActionEvent actionEvent) {
JScrollBar verticalScrollBar = scrollPane.getVerticalScrollBar();
JScrollBar horizontalScrollBar = scrollPane.getHorizontalScrollBar();
verticalScrollBar.setValue(verticalScrollBar.getMinimum());
horizontalScrollBar.setValue(horizontalScrollBar.getMinimum());
}
}
JScrollPane Corner
import java.awt.BorderLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
public class CornerSample {
public static void main(String args[]) {
JFrame frame = new JFrame("Cornering Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Icon miniLogo = new ImageIcon("logo.gif");
Icon acrossLogo = new ImageIcon("logo-across.jpg");
Icon downLogo = new ImageIcon("logo-down.jpg");
Icon bookCover = new ImageIcon("puzzlebook.jpg");
JLabel logoLabel = new JLabel(miniLogo);
JLabel columnLabel = new JLabel(acrossLogo);
JLabel rowLabel = new JLabel(downLogo);
JLabel coverLabel = new JLabel(bookCover);
JScrollPane scrollPane = new JScrollPane(coverLabel);
scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, logoLabel);
scrollPane.setColumnHeaderView(columnLabel);
scrollPane.setRowHeaderView(rowLabel);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
JScrollPane to hold scrollable component
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.Box;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
public class Main {
public static void main(String args[]) {
JFrame f = new JFrame();
f.setLayout(new FlowLayout());
f.setSize(240, 250);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane jscrlpLabel = new JScrollPane(new JLabel(
"<html>A<br>B<br>C<br>D<br>E<br>F<br>G<br>H<br></html>."));
jscrlpLabel.setPreferredSize(new Dimension(200, 100));
JLabel label = new JLabel("Option");
JCheckBox a = new JCheckBox("A");
JCheckBox b = new JCheckBox("B");
JCheckBox c = new JCheckBox("C");
JCheckBox d = new JCheckBox("D");
JCheckBox e = new JCheckBox("E");
Box box = Box.createVerticalBox();
box.add(label);
box.add(a);
box.add(b);
box.add(c);
box.add(d);
box.add(e);
JScrollPane jscrlpBox = new JScrollPane(box);
jscrlpBox.setPreferredSize(new Dimension(140, 90));
f.add(jscrlpLabel);
f.add(jscrlpBox);
f.setVisible(true);
}
}
Listening for Scrollbar Value Changes in a JScrollPane Container
import java.awt.Adjustable;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Main {
public static void main(String[] argv) throws Exception {
JTextArea textArea = new JTextArea();
JScrollPane pane = new JScrollPane(textArea);
// Listen for value changes in the scroll pane"s scrollbars
AdjustmentListener listener = new MyAdjustmentListener();
pane.getHorizontalScrollBar().addAdjustmentListener(listener);
pane.getVerticalScrollBar().addAdjustmentListener(listener);
}
}
class MyAdjustmentListener implements AdjustmentListener {
public void adjustmentValueChanged(AdjustmentEvent evt) {
Adjustable source = evt.getAdjustable();
if (evt.getValueIsAdjusting()) {
return;
}
int orient = source.getOrientation();
if (orient == Adjustable.HORIZONTAL) {
System.out.println("from horizontal scrollbar");
} else {
System.out.println("from vertical scrollbar");
}
int type = evt.getAdjustmentType();
switch (type) {
case AdjustmentEvent.UNIT_INCREMENT:
System.out.println("Scrollbar was increased by one unit");
break;
case AdjustmentEvent.UNIT_DECREMENT:
System.out.println("Scrollbar was decreased by one unit");
break;
case AdjustmentEvent.BLOCK_INCREMENT:
System.out.println("Scrollbar was increased by one block");
break;
case AdjustmentEvent.BLOCK_DECREMENT:
System.out.println("Scrollbar was decreased by one block");
break;
case AdjustmentEvent.TRACK:
System.out.println("The knob on the scrollbar was dragged");
break;
}
int value = evt.getValue();
}
}
Make the scrollbars always appear
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Main {
public static void main(String[] argv) throws Exception {
JTextArea textArea = new JTextArea();
JScrollPane pane = new JScrollPane(textArea);
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
}
}
Make the scrollbars never appear
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Main {
public static void main(String[] argv) throws Exception {
JTextArea textArea = new JTextArea();
JScrollPane pane = new JScrollPane(textArea);
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
}
}
ScrollBar Pieces
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollBar;
public class ScrollBarPieces {
public static void main(String args[]) {
JScrollBar oneJScrollBar = new JScrollBar(JScrollBar.HORIZONTAL);
String title = (args.length == 0 ? "ScrollBar Sample" : args[0]);
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
contentPane.add(oneJScrollBar, BorderLayout.NORTH);
frame.setSize(200, 44);
frame.setVisible(true);
}
}
Use Adjustment Events in Swing
import java.awt.BorderLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.SwingConstants;
public class Main extends JFrame implements AdjustmentListener {
JScrollBar bar = new JScrollBar(SwingConstants.HORIZONTAL, 50, 10, 0, 100);
public Main() {
setSize(350, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
bar.addAdjustmentListener(this);
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout());
pane.add(bar, "South");
setContentPane(pane);
}
public static void main(String[] arguments) {
JFrame frame = new Main();
frame.setVisible(true);
}
public void adjustmentValueChanged(AdjustmentEvent evt) {
Object source = evt.getSource();
int newValue = bar.getValue();
System.out.println(newValue);
repaint();
}
}