Java Swing How to - Extend JLabel to Scrollable Label








Question

We would like to know how to extend JLabel to Scrollable Label.

Answer

import java.awt.Dimension;
import java.awt.Rectangle;
/*from  w w w . j av a2  s .  com*/
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.Scrollable;

public class Main {
  public static void main(String[] args) {
    JFrame f = new JFrame();

    ImageIcon ii = new ImageIcon("largeJava2sLogo.gif");
    JScrollPane jsp = new JScrollPane(new ScrollableLabel(ii));
    f.getContentPane().add(jsp);
    f.setSize(300, 250);
    f.setVisible(true);

  }
}

class ScrollableLabel extends JLabel implements Scrollable {
  public ScrollableLabel(ImageIcon i) {
    super(i);
  }

  public Dimension getPreferredScrollableViewportSize() {
    return getPreferredSize();
  }

  public int getScrollableBlockIncrement(Rectangle r, int orietation,
      int direction) {
    return 10;
  }

  public boolean getScrollableTracksViewportHeight() {
    return false;
  }

  public boolean getScrollableTracksViewportWidth() {
    return false;
  }

  public int getScrollableUnitIncrement(Rectangle r, int orientation,
      int direction) {
    return 10;
  }

}