Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

Swing Chapter 7. (The basics) Scrolling Panes. Easy for reading, Click here!

Custom Search
Swing Chapter 7. (The basics) Scrolling Panes. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 3/3 



Previous Page Previous Page (2/3)
Subpages: 1. JScrollPane
2. Grab-and-drag scrolling
3. Scrolling programmatically

7.3    Scrolling programmatically

We are certainly not required to use a JScrollPane for scrolling. We can place a component in a JViewport and control the scrolling ourselves if we like. This is what JViewport was designed for, it just happens to be used by JScrollPane as well. We've constructed this example to show how to implement our own scrolling in a JViewport. Four buttons are used for scrolling. We enable and disable these buttons based on whether the view component is at any of its extremities. These buttons are assigned keyboard mnemonics which we can use as an alternative to clicking.

This example also shows how to use a ChangeListener to capture ChangeEvents that are fired when the JViewport changes state. The reason we need to capture these events is that when our viewport is resized bigger than its view component child, the scrolling buttons should become disabled. If these buttons are disabled and the viewport is then resized so that it is no longer bigger than its child view component, the buttons should then become enabled. It is quite simple to capture and process these events as you will see below. (As with all of the examples we have presented, it may help if you run this example before stepping through the code.)

Figure 7.4 Programmatic scrolling with JViewport.

<<file figure7-4.gif>>

The Code: ButtonScroll.java

see \Chapter7\5

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;

public class ButtonScroll extends JFrame

{

  protected JViewport m_viewport;

  protected JButton m_up;

  protected JButton m_down;

  protected JButton m_left;

  protected JButton m_right;

  protected int m_pgVert;

  protected int m_pgHorz;

  public ButtonScroll() {

    super("Scrolling Programmatically");

    setSize(400, 400);

    getContentPane().setLayout(new BorderLayout());

    ImageIcon shuttle = new ImageIcon("shuttle.gif");

    m_pgVert = shuttle.getIconHeight()/5;

    m_pgHorz = shuttle.getIconWidth()/5;

    JLabel lbl = new JLabel(shuttle);

    m_viewport = new JViewport();

    m_viewport.setView(lbl);

    m_viewport.addChangeListener(new ChangeListener() {

      public void stateChanged(ChangeEvent e) {

        enableButtons(

          ButtonScroll.this.m_viewport.getViewPosition());

      }

    });

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

    JPanel pv = new JPanel(new BorderLayout());

    m_up = createButton("up", 'u');

    ActionListener lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        movePanel(0, -1);

      }

    };

    m_up.addActionListener(lst);

    pv.add(m_up, BorderLayout.NORTH);

    m_down = createButton("down", 'd');

    lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        movePanel(0, 1);

      }

    };

    m_down.addActionListener(lst);

    pv.add(m_down, BorderLayout.SOUTH);

    getContentPane().add(pv, BorderLayout.EAST);

    JPanel ph = new JPanel(new BorderLayout());

    m_left = createButton("left", 'l');

    lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        movePanel(-1, 0);

      }

    };

    m_left.addActionListener(lst);

    ph.add(m_left, BorderLayout.WEST);

    m_right = createButton("right", 'r');

    lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        movePanel(1, 0);

      }

    };

    m_right.addActionListener(lst);

    ph.add(m_right, 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(new ImageIcon(name+"1.gif"));

    btn.setPressedIcon(new ImageIcon(name+"2.gif"));

    btn.setDisabledIcon(new ImageIcon(name+"3.gif"));

    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 = m_viewport.getViewPosition();

    pt.x += m_pgHorz*xmove;

    pt.y += m_pgVert*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);

    m_viewport.setViewPosition(pt);

    enableButtons(pt);

  }

  protected void enableButtons(Point pt) {

    if (pt.x == 0)

      enableComponent(m_left, false);

    else enableComponent(m_left, true);

    if (pt.x >= getMaxXExtent())

      enableComponent(m_right, false);

    else enableComponent(m_right, true);

    if (pt.y == 0)

      enableComponent(m_up, false);

    else enableComponent(m_up, true);

    if (pt.y >= getMaxYExtent())

      enableComponent(m_down, false);

    else enableComponent(m_down, true);

  }

  protected void enableComponent(JComponent c, boolean b) {

    if (c.isEnabled() != b)

      c.setEnabled(b);

  }

  protected int getMaxXExtent() {

    return m_viewport.getView().getWidth()-m_viewport.getWidth();

  }

  protected int getMaxYExtent() {

    return m_viewport.getView().getHeight()-m_viewport.getHeight();

  }

  public static void main(String argv[])  {

    new ButtonScroll();

  }

}

Understanding the Code

Class ButtonScroll

Several instance variables are declared:

JViewport m_viewport: viewport to display a large image.

JButton m_up: push button to scroll up programmatically.

JButton m_down: push button to scroll down programmatically.

JButton m_left: push button to scroll left programmatically.

JButton m_right: push button to scroll right programmatically.

int m_pgVert: number of pixels for a vertical scroll.

int m_pgHorz: number of pixels for a horizontal scroll.

The constructor of the ButtonScroll class creates and initializes the GUI components for this example. A BorderLayout is used to manage the components in this frame's content pane. JLabel lbl holding a large image is placed in the viewport, m_viewport, to provide programmatic viewing capabilities. This JViewport is added to the center of our frame.

As we mentioned above, we need to capture the ChangeEvents that are fired when our JViewport changes size so that we can enable and disable our buttons accordingly. We do this by simply attaching a ChangeListener to our viewport and call our enableButtons() method (see below) from stateChanged():

    m_viewport.addChangeListener(new ChangeListener() {

      public void stateChanged(ChangeEvent e) {

        enableButtons(

          ButtonScroll.this.m_viewport.getViewPosition());

      }

    });

Two buttons m_up and m_down are created for scrolling in the vertical direction. Method createButton() is used to create a new JButton component and set a group of properties for it (see below). Each of the new buttons receives an ActionListener which calls the movePanel() method in response to a mouse click. These two buttons are added to the intermediate container, JPanel pv, which is added to the EAST side of our frame's content pane. Similarly, two buttons, m_left and m_right, are created for scrolling in the horizontal direction and added to the SOUTH region of the content pane.

Method createButton() creates a new JButton component and sets a group of properties for it. This method takes two parameters: the name of the scrolling direction as a String and the button's mnemonic as a char. This method assumes that three image files are prepared:

name1.gif: the default icon.

name2.gif: the pressed icon.

name3.gif: the disabled icon.

These images are loaded as ImageIcons and attached to the button with the associated setXX() method:

        JButton btn = new JButton(new ImageIcon(name+"1.gif"));

        btn.setPressedIcon(new ImageIcon(name+"2.gif"));

        btn.setDisabledIcon(new ImageIcon(name+"3.gif"));

        btn.setToolTipText("Moves "+name);

        btn.setBorderPainted(false);

        btn.setMargin(new Insets(0, 0, 0, 0));

        btn.setContentAreaFilled(false);

        btn.setMnemonic(mnemonic);

        return btn;

Then we remove any border or content area painting, so the presentation of our button is completely determined by our icons. Finally we set the tool tip text and mnemonic and return that component instance.

Method movePanel() programmatically scrolls the image in the viewport in the direction determined by two parameters: xmove and ymove. These parameters can have values -1, 0, or 1. To determine the actual amount of scrolling we multiply these parameters by m_pgHorz (m_pgVert). Local variable Point pt determines a new viewport position. It is limited so the resulting view will not display any empty space (not belonging to the displaying image), similar to how we enforce the viewport view position in the grab-and-drag scrolling example above. Finally, method setViewPosition() is called to scroll to the new position and enableButtons() enables/disables buttons according to the new position:

    Point pt = m_viewport.getViewPosition();

    pt.x += m_pgHorz*xmove;

    pt.y += m_pgVert*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);

    m_viewport.setViewPosition(pt);

    enableButtons(pt);

Method enableButtons() disables a button if scrolling in the corresponding direction is not possible and enables it otherwise. For example, if the viewport position's x coordinate is 0 we can disable the scroll left button (remember that the view position will never be negative, as enforced by JViewport):

    if (pt.x <= 0)

      enableComponent(m_left, false);

    else enableComponent(m_left, true);

...Similarly, if the viewport position's x coordinate is greater than or equal to our maximum allowable x position (determined by getMaxXExtent()) we disable the scroll right button:

    if (pt.x >= getMaxXExtent())

      enableComponent(m_right, false);

    else enableComponent(m_right, true);

Methods getMaxXExtent() and getMaxYExtent() return the maximum coordinates available for scrolling in the horizontal (vertical direction) by subtracting the appropriate viewport dimension from the appropriate dimension of the child component.

Running the Code

Note: The shuttle image for this example was found at http://shuttle.nasa.gov/sts-95/images/esc/

Note how different images completely determine the presentation of our buttons. Press the buttons and note how the image is scrolled programmatically. Use the keyboard mnemonic as an alternative way to press the buttons, and note how this mnemonic is displayed in the tool tip text. Note how a button is disabled when scrolling in the corresponding direction is no longer available, and are enabled otherwise. Now try resizing the frame and note how the buttons will change state depending on whether the viewport is bigger or smaller than its child component.



[ Return to Swing (Book) ]


Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color


[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3


[ More in News Section ]


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy