Java/Swing JFC/Scrollpane

Материал из Java эксперт
Перейти к: навигация, поиск

A simple JScrollPane demonstration

 
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly 
*/
// ScrollDemo.java
//A simple JScrollPane demonstration.
//
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
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]));
          } 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();
  }
}





A simple JScrollPane for a JList component

 
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly 
*/
// ScrollList.java
//A simple JScrollPane for a JList component.
//
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class ScrollList extends JFrame {
  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);
  }
}





Controlling the scrollbars in a JScrollPane

 
// : c14:JScrollPanes.java
// Controlling the scrollbars in a JScrollPane.
// <applet code=JScrollPanes width=300 height=725></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.Border;
public class JScrollPanes extends JApplet {
  private JButton b1 = new JButton("Text Area 1"), b2 = new JButton(
      "Text Area 2"), b3 = new JButton("Replace Text"), b4 = new JButton(
      "Insert Text");
  private JTextArea t1 = new JTextArea("t1", 1, 20), t2 = new JTextArea("t2",
      4, 20), t3 = new JTextArea("t3", 1, 20), t4 = new JTextArea("t4",
      10, 10), t5 = new JTextArea("t5", 4, 20), t6 = new JTextArea("t6",
      10, 10);
  private JScrollPane sp3 = new JScrollPane(t3,
      JScrollPane.VERTICAL_SCROLLBAR_NEVER,
      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), sp4 = new JScrollPane(t4,
      JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), sp5 = new JScrollPane(t5,
      JScrollPane.VERTICAL_SCROLLBAR_NEVER,
      JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS), sp6 = new JScrollPane(t6,
      JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
      JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
  class B1L implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      t5.append(t1.getText() + "\n");
    }
  }
  class B2L implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      t2.setText("Inserted by Button 2");
      t2.append(": " + t1.getText());
      t5.append(t2.getText() + "\n");
    }
  }
  class B3L implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      String s = " Replacement ";
      t2.replaceRange(s, 3, 3 + s.length());
    }
  }
  class B4L implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      t2.insert(" Inserted ", 10);
    }
  }
  public void init() {
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    // Create Borders for components:
    Border brd = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK);
    t1.setBorder(brd);
    t2.setBorder(brd);
    sp3.setBorder(brd);
    sp4.setBorder(brd);
    sp5.setBorder(brd);
    sp6.setBorder(brd);
    // Initialize listeners and add components:
    b1.addActionListener(new B1L());
    cp.add(b1);
    cp.add(t1);
    b2.addActionListener(new B2L());
    cp.add(b2);
    cp.add(t2);
    b3.addActionListener(new B3L());
    cp.add(b3);
    b4.addActionListener(new B4L());
    cp.add(b4);
    cp.add(sp3);
    cp.add(sp4);
    cp.add(sp5);
    cp.add(sp6);
  }
  public static void main(String[] args) {
    run(new JScrollPanes(), 300, 725);
  }
  public static void run(JApplet applet, int width, int height) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(applet);
    frame.setSize(width, height);
    applet.init();
    applet.start();
    frame.setVisible(true);
  }
} ///:~





Create a scrollable list

 
import javax.swing.JList;
import javax.swing.JScrollPane;
public class Main {
  public static void main(String[] argv) throws Exception {
    JList list = new JList();
    JScrollPane scrollableList = new JScrollPane(list);
  }
}





Creating a JScrollPane Container

 
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a scrollable text area
    JTextArea textArea = new JTextArea();
    JScrollPane scrollableTextArea = new JScrollPane(textArea);
  }
}





Customized ScrollPane

 
import java.awt.Dimension;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
public class CustomScrollPane extends JPanel {
  protected JScrollBar verticalBar = new JScrollBar(JScrollBar.VERTICAL, 0, 0, 0, 0);
  protected JScrollBar horizontalBar = new JScrollBar(JScrollBar.HORIZONTAL, 0, 0, 0, 0);
  protected CustomViewport viewport = new CustomViewport();
  protected JComponent innerComponent;
  public CustomScrollPane(JComponent comp) {
    setLayout(null);
    
    add(viewport);
    innerComponent = comp;
    viewport.add(innerComponent);
    
    verticalBar.setUnitIncrement(5);
    add(verticalBar);
    horizontalBar.setUnitIncrement(5);
    add(horizontalBar);
    AdjustmentListener lst = new AdjustmentListener() {
      public void adjustmentValueChanged(AdjustmentEvent e) {
        viewport.doLayout();
      }
    };
    verticalBar.addAdjustmentListener(lst);
    horizontalBar.addAdjustmentListener(lst);
  }
  public void doLayout() {
    Dimension size = getSize();
    Dimension innerComponentSize = innerComponent.getPreferredSize();
    Dimension verticalBarSize = verticalBar.getPreferredSize();
    Dimension horizontalBarSize = horizontalBar.getPreferredSize();
    int width = Math.max(size.width - verticalBarSize.width - 1, 0);
    int height = Math.max(size.height - horizontalBarSize.height - 1, 0);
    viewport.setBounds(0, 0, width, height);
    verticalBar.setBounds(width + 1, 0, verticalBarSize.width, height);
    horizontalBar.setBounds(0, height + 1, width, horizontalBarSize.height);
    int maxWidth = Math.max(innerComponentSize.width - width, 0);
    horizontalBar.setMaximum(maxWidth);
    horizontalBar.setBlockIncrement(maxWidth / 5);
    horizontalBar.setEnabled(maxWidth > 0);
    int maxHeight = Math.max(innerComponentSize.height - height, 0);
    verticalBar.setMaximum(maxHeight);
    verticalBar.setBlockIncrement(maxHeight / 5);
    verticalBar.setEnabled(maxHeight > 0);
    horizontalBar.setVisibleAmount(horizontalBar.getBlockIncrement());
    verticalBar.setVisibleAmount(verticalBar.getBlockIncrement());
  }
  public Dimension getPreferredSize() {
    Dimension innerComponmentSize = innerComponent.getPreferredSize();
    Dimension verticalBarSize = verticalBar.getPreferredSize();
    Dimension d2 = horizontalBar.getPreferredSize();
    Dimension horizontalBarSize = new Dimension(innerComponmentSize.width
        + verticalBarSize.width, innerComponmentSize.height + d2.height);
    return horizontalBarSize;
  }
  class CustomViewport extends JPanel {
    public CustomViewport(){
      setLayout(null);  
    }
    
    public void doLayout() {
      Dimension innerComponentSize = innerComponent.getPreferredSize();
      int x = horizontalBar.getValue();
      int y = verticalBar.getValue();
      innerComponent.setBounds(-x, -y, innerComponentSize.width,
          innerComponentSize.height);
    }
  }
  public static void main(String[] args) {
    JFrame f = new JFrame("JScrollBar Demo");
    f.setSize(300, 250);
    ImageIcon icon = new ImageIcon("earth.jpg");
    CustomScrollPane myScrollPane = new CustomScrollPane(new JLabel(icon));
    f.getContentPane().add(myScrollPane);
    WindowListener wndCloser = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    };
    f.addWindowListener(wndCloser);
    f.setVisible(true);
    
  }
  
}





JScrollPane with row and column headers

 
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly 
*/
// ScrollDemo2.java
//Another JScrollPane demonstration. This version activates some of the
//features of JScrollPane such as row and column headers.
//
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.ScrollPaneConstants;
public class ScrollDemo2 extends JFrame {
  JScrollPane scrollpane;
  public ScrollDemo2() {
    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]));
          } 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);
    // Add in some JViewports for the column and row headers
    JViewport jv1 = new JViewport();
    jv1.setView(new JLabel(new ImageIcon("columnlabel.gif")));
    scrollpane.setColumnHeader(jv1);
    JViewport jv2 = new JViewport();
    jv2.setView(new JLabel(new ImageIcon("rowlabel.gif")));
    scrollpane.setRowHeader(jv2);
    // And throw in an information button
    JButton jb1 = new JButton(new ImageIcon("question.gif"));
    jb1.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        JOptionPane.showMessageDialog(null,
            "This is an Active Corner!", "Information",
            JOptionPane.INFORMATION_MESSAGE);
      }
    });
    scrollpane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, jb1);
    getContentPane().add(scrollpane, BorderLayout.CENTER);
  }
  public static void main(String args[]) {
    new ScrollDemo2();
  }
}





JViewport: Move and View

 
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JViewport;
import javax.swing.KeyStroke;
public class MoveViewSample {
  public static final int INCREASE = 0; // direction
  public static final int DECREASE = 1; // direction
  public static final int X_AXIS = 0; // axis
  public static final int Y_AXIS = 1; // axis
  public static final int UNIT = 0; // type
  public static final int BLOCK = 1; // type
  static class MoveAction extends AbstractAction {
    JViewport viewport;
    int direction;
    int axis;
    int type;
    public MoveAction(JViewport viewport, int direction, int axis, int type) {
      if (viewport == null) {
        throw new IllegalArgumentException(
            "null viewport not permitted");
      }
      this.viewport = viewport;
      this.direction = direction;
      this.axis = axis;
      this.type = type;
    }
    public void actionPerformed(ActionEvent actionEvent) {
      Dimension extentSize = viewport.getExtentSize();
      int horizontalMoveSize = 0;
      int verticalMoveSize = 0;
      if (axis == X_AXIS) {
        if (type == UNIT) {
          horizontalMoveSize = 1;
        } else { // type == BLOCK
          horizontalMoveSize = extentSize.width;
        }
      } else { // axis == Y_AXIS
        if (type == UNIT) {
          verticalMoveSize = 1;
        } else { // type == BLOCK
          verticalMoveSize = extentSize.height;
        }
      }
      if (direction == DECREASE) {
        horizontalMoveSize = -horizontalMoveSize;
        verticalMoveSize = -verticalMoveSize;
      }
      // Translate origin by some amount
      Point origin = viewport.getViewPosition();
      origin.x += horizontalMoveSize;
      origin.y += verticalMoveSize;
      // set new viewing origin
      viewport.setViewPosition(origin);
    }
  }
  public static void main(String args[]) {
    JFrame frame = new JFrame("JViewport Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Icon icon = new ImageIcon("dog.jpg");
    JLabel dogLabel = new JLabel(icon);
    JViewport viewport = new JViewport();
    viewport.setView(dogLabel);
    InputMap inputMap = viewport
        .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    ActionMap actionMap = viewport.getActionMap();
    // Up key moves view up unit
    Action upKeyAction = new MoveAction(viewport, DECREASE, Y_AXIS, UNIT);
    KeyStroke upKey = KeyStroke.getKeyStroke("UP");
    inputMap.put(upKey, "up");
    actionMap.put("up", upKeyAction);
    // Down key moves view down unit
    Action downKeyAction = new MoveAction(viewport, INCREASE, Y_AXIS, UNIT);
    KeyStroke downKey = KeyStroke.getKeyStroke("DOWN");
    inputMap.put(downKey, "down");
    actionMap.put("down", downKeyAction);
    // Left key moves view left unit
    Action leftKeyAction = new MoveAction(viewport, DECREASE, X_AXIS, UNIT);
    KeyStroke leftKey = KeyStroke.getKeyStroke("LEFT");
    inputMap.put(leftKey, "left");
    actionMap.put("left", leftKeyAction);
    // Right key moves view right unit
    Action rightKeyAction = new MoveAction(viewport, INCREASE, X_AXIS, UNIT);
    KeyStroke rightKey = KeyStroke.getKeyStroke("RIGHT");
    inputMap.put(rightKey, "right");
    actionMap.put("right", rightKeyAction);
    // PgUp key moves view up block
    Action pgUpKeyAction = new MoveAction(viewport, DECREASE, Y_AXIS, BLOCK);
    KeyStroke pgUpKey = KeyStroke.getKeyStroke("PAGE_UP");
    inputMap.put(pgUpKey, "pgUp");
    actionMap.put("pgUp", pgUpKeyAction);
    // PgDn key moves view down block
    Action pgDnKeyAction = new MoveAction(viewport, INCREASE, Y_AXIS, BLOCK);
    KeyStroke pgDnKey = KeyStroke.getKeyStroke("PAGE_DOWN");
    inputMap.put(pgDnKey, "pgDn");
    actionMap.put("pgDn", pgDnKeyAction);
    // Shift-PgUp key moves view left block
    Action shiftPgUpKeyAction = new MoveAction(viewport, DECREASE, X_AXIS,
        BLOCK);
    KeyStroke shiftPgUpKey = KeyStroke.getKeyStroke("shift PAGE_UP");
    inputMap.put(shiftPgUpKey, "shiftPgUp");
    actionMap.put("shiftPgUp", shiftPgUpKeyAction);
    // Shift-PgDn key moves view right block
    Action shiftPgDnKeyAction = new MoveAction(viewport, INCREASE, X_AXIS,
        BLOCK);
    KeyStroke shiftPgDnKey = KeyStroke.getKeyStroke("shift PAGE_DOWN");
    inputMap.put(shiftPgDnKey, "shiftPgDn");
    actionMap.put("shiftPgDn", shiftPgDnKeyAction);
    Container contentPane = frame.getContentPane();
    contentPane.add(viewport, BorderLayout.CENTER);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





Scrolling Programmatically

 
import java.awt.BorderLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JViewport;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ButtonScroll extends JFrame {
  protected JViewport viewport;
  protected JButton upButton;
  protected JButton downButton;
  protected JButton leftButton;
  protected JButton rightButton;
  protected int pgVertical;
  protected int pgHorzontal;
  public ButtonScroll() {
    super("Scrolling Programmatically");
    setSize(400, 400);
    getContentPane().setLayout(new BorderLayout());
    ImageIcon shuttle = new ImageIcon("largejexpLogo.GIF");
    pgVertical = shuttle.getIconHeight() / 5;
    pgHorzontal = shuttle.getIconWidth() / 5;
    JLabel lbl = new JLabel(shuttle);
    viewport = new JViewport();
    viewport.setView(lbl);
    viewport.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
        enableButtons(ButtonScroll.this.viewport.getViewPosition());
      }
    });
    getContentPane().add(viewport, BorderLayout.CENTER);
    JPanel pv = new JPanel(new BorderLayout());
    upButton = createButton("up", "u");
    ActionListener lst = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        movePanel(0, -1);
      }
    };
    upButton.addActionListener(lst);
    pv.add(upButton, BorderLayout.NORTH);
    downButton = createButton("down", "d");
    lst = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        movePanel(0, 1);
      }
    };
    downButton.addActionListener(lst);
    pv.add(downButton, BorderLayout.SOUTH);
    getContentPane().add(pv, BorderLayout.EAST);
    JPanel ph = new JPanel(new BorderLayout());
    leftButton = createButton("left", "l");
    lst = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        movePanel(-1, 0);
      }
    };
    leftButton.addActionListener(lst);
    ph.add(leftButton, BorderLayout.WEST);
    rightButton = createButton("right", "r");
    lst = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        movePanel(1, 0);
      }
    };
    rightButton.addActionListener(lst);
    ph.add(rightButton, BorderLayout.EAST);
    getContentPane().add(ph, BorderLayout.SOUTH);
    WindowListener wndCloser = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    };
    addWindowListener(wndCloser);
    setVisible(true);
    movePanel(0, 0);
  }
  protected JButton createButton(String name, char mnemonics) {
    JButton btn = new JButton(name );
    btn.setToolTipText("Move " + name);
    btn.setBorderPainted(false);
    btn.setMargin(new Insets(0, 0, 0, 0));
    btn.setContentAreaFilled(false);
    btn.setMnemonic(mnemonics);
    return btn;
  }
  protected void movePanel(int xmove, int ymove) {
    Point pt = viewport.getViewPosition();
    pt.x += pgHorzontal * xmove;
    pt.y += pgVertical * ymove;
    pt.x = Math.max(0, pt.x);
    pt.x = Math.min(getMaxXExtent(), pt.x);
    pt.y = Math.max(0, pt.y);
    pt.y = Math.min(getMaxYExtent(), pt.y);
    viewport.setViewPosition(pt);
    enableButtons(pt);
  }
  protected void enableButtons(Point pt) {
    if (pt.x == 0)
      enableComponent(leftButton, false);
    else
      enableComponent(leftButton, true);
    if (pt.x >= getMaxXExtent())
      enableComponent(rightButton, false);
    else
      enableComponent(rightButton, true);
    if (pt.y == 0)
      enableComponent(upButton, false);
    else
      enableComponent(upButton, true);
    if (pt.y >= getMaxYExtent())
      enableComponent(downButton, false);
    else
      enableComponent(downButton, true);
  }
  protected void enableComponent(JComponent c, boolean b) {
    if (c.isEnabled() != b)
      c.setEnabled(b);
  }
  protected int getMaxXExtent() {
    return viewport.getView().getWidth() - viewport.getWidth();
  }
  protected int getMaxYExtent() {
    return viewport.getView().getHeight() - viewport.getHeight();
  }
  public static void main(String argv[]) {
    new ButtonScroll();
  }
}





Scrollpane ruler

 
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
public class HeaderDemo extends JFrame {
  private JLabel label = new JLabel(new ImageIcon("largejexpLogo.gif"));
  public HeaderDemo() {
    super("JScrollPane Demo");
    JScrollPane scrollPane = new JScrollPane(label);
    JLabel[] corners = new JLabel[4];
    for (int i = 0; i < 4; i++) {
      corners[i] = new JLabel();
      corners[i].setBackground(Color.white);
      corners[i].setOpaque(true);
    }
    JLabel rowheader = new JLabel() {
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Rectangle rect = g.getClipBounds();
        for (int i = 50 - (rect.y % 50); i < rect.height; i += 50) {
          g.drawLine(0, rect.y + i, 3, rect.y + i);
          g.drawString("" + (rect.y + i), 6, rect.y + i + 3);
        }
      }
      public Dimension getPreferredSize() {
        return new Dimension(25, (int) label.getPreferredSize()
            .getHeight());
      }
    };
    rowheader.setBackground(Color.white);
    rowheader.setOpaque(true);
    JLabel columnheader = new JLabel() {
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Rectangle r = g.getClipBounds();
        for (int i = 50 - (r.x % 50); i < r.width; i += 50) {
          g.drawLine(r.x + i, 0, r.x + i, 3);
          g.drawString("" + (r.x + i), r.x + i - 10, 16);
        }
      }
      public Dimension getPreferredSize() {
        return new Dimension((int) label.getPreferredSize().getWidth(),
            25);
      }
    };
    columnheader.setBackground(Color.white);
    columnheader.setOpaque(true);
    scrollPane.setRowHeaderView(rowheader);
    scrollPane.setColumnHeaderView(columnheader);
    scrollPane.setCorner(JScrollPane.LOWER_LEFT_CORNER, corners[0]);
    scrollPane.setCorner(JScrollPane.LOWER_RIGHT_CORNER, corners[1]);
    scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, corners[2]);
    scrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER, corners[3]);
    getContentPane().add(scrollPane);
    setSize(400, 300);
    setVisible(true);
  }
  public static void main(String[] args) {
    new HeaderDemo();
  }
}





ScrollPane Sample

 
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 ScrollSample {
  public static void main(String args[]) {
    String title = (args.length == 0 ? "JScrollPane Sample" : args[0]);
    JFrame frame = new JFrame(title);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Icon icon = new ImageIcon("dog.jpg");
    JLabel dogLabel = new JLabel(icon);
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setViewportView(dogLabel);
    //    scrollPane.getViewport().setView(dogLabel);
    frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





ScrollPane with image

 
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
public class ScrollPaneDemo extends JFrame {
  public ScrollPaneDemo() {
    super("JScrollPane Demo");
    ImageIcon ii = new ImageIcon("largejexpLogo.jpg");
    JScrollPane jsp = new JScrollPane(new JLabel(ii));
    getContentPane().add(jsp);
    setSize(300, 250);
    setVisible(true);
  }
  public static void main(String[] args) {
    new ScrollPaneDemo();
  }
}





Watermark JScrollPane

 
/*
Swing Hacks Tips and Tools for Killer GUIs
By Joshua Marinacci, Chris Adamson
First Edition June 2005  
Series: Hacks
ISBN: 0-596-00907-0
Pages: 542
website: http://www.oreilly.ru/catalog/swinghks/
*/
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JViewport;
public class ScrollPaneWatermark extends JViewport {
  BufferedImage fgimage, bgimage;
  TexturePaint texture;
  public ScrollPaneWatermark() {
    super();
    // setOpaque(false);
  }
  public void setBackgroundTexture(URL url) throws IOException {
    bgimage = ImageIO.read(url);
    Rectangle rect = new Rectangle(0, 0, bgimage.getWidth(null), bgimage.getHeight(null));
    texture = new TexturePaint(bgimage, rect);
  }
  public void setForegroundBadge(URL url) throws IOException {
    fgimage = ImageIO.read(url);
  }
  public void paintComponent(Graphics g) {
    // do the superclass behavior first
    super.paintComponent(g);
    // paint the texture
    if (texture != null) {
      Graphics2D g2 = (Graphics2D) g;
      g2.setPaint(texture);
      g.fillRect(0, 0, getWidth(), getHeight());
    }
  }
  public void paintChildren(Graphics g) {
    super.paintChildren(g);
    if (fgimage != null) {
      g.drawImage(fgimage, getWidth() - fgimage.getWidth(null), 0, null);
    }
  }
  public void setView(JComponent view) {
    view.setOpaque(false);
    super.setView(view);
  }
  public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame();
    JTextArea ta = new JTextArea();
    for (int i = 0; i < 1000; i++) {
      ta.append(Integer.toString(i) + "  ");
    }
    ta.setLineWrap(true);
    ta.setWrapStyleWord(true);
    // ta.setOpaque(false);
    ScrollPaneWatermark watermark = new ScrollPaneWatermark();
    watermark.setBackgroundTexture(new File("background.jpg").toURL());
    watermark.setForegroundBadge(new File("foreground.png").toURL());
    watermark.setView(ta);
    JScrollPane scroll = new JScrollPane();
    scroll.setViewport(watermark);
    frame.getContentPane().add(scroll);
    frame.pack();
    frame.setSize(600, 600);
    frame.setVisible(true);
  }
}