Scrollpane in Java Swing

In this section, you will study how to scroll the drawing on canvas. For this, we have used class Canvas which extends the class JPanel.

Scrollpane in Java Swing

In this section, you will study how to scroll the drawing on canvas. For this, we have used class Canvas which extends the class JPanel.

Scrollpane in Java Swing

Scrollpane in Java Swing

     

Use Canvas with ScrollPane in swing.

In this section, you will study how to scroll the drawing on canvas. For this, we have used class Canvas which extends the class JPanel. The method setSize() resizes the component by calling the method getPreferredSize() of Component class which returns the dimension object showing the component's preferred size. The class Ellipse2D is used to draw a circle.


Following code adds a scrollpane on canvas:

getContentPane().add(new JScrollPane(new Canvas()));

The package javax.swing implements a class JScrollPane which provides the scrollable view of the component. 

Here is the code of ScrollPaneOnCanvas.java

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;

public class ScrollPaneOnCanvas extends JFrame {
 class Canvas extends JPanel {
 public Canvas () {
 setSize(getPreferredSize());
 Canvas.this.setBackground(Color.white);
 }
 public Dimension getPreferredSize() {
 return new Dimension(600, 400);
 }

 public void paintComponent(Graphics g) {
 super.paintComponent(g);
 Graphics2D g2d = (Graphics2D) g;
 Ellipse2D ellipse = new Ellipse2D.Double(0, 0, 100, 100);
 g2d.setColor(Color.cyan);
 g2d.translate(10, 10);
 g2d.draw(ellipse);
 g2d.fill(ellipse);
  }
  }
 public ScrollPaneOnCanvas() {
 super("Swing Application");
 setSize(300, 300);
 getContentPane().add(new JScrollPane(new Canvas()));
  }
 public static void main(String[] args) {
 ScrollPaneOnCanvas canvas = new ScrollPaneOnCanvas();
 canvas.show();
  }

Output will be displayed as:

Download Source Code