Java Swing How to - Use getClipBounds in combination with JScrollPane








Question

We would like to know how to use getClipBounds in combination with JScrollPane.

Answer

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;
/*from   w w w.ja  va 2  s  . c  o m*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;

public class Main extends JPanel {
  public Main() {
    setPreferredSize(new Dimension(2000, 2000));
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new JScrollPane(new Main()));
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }

  @Override
  protected void paintComponent(Graphics g) {
    Rectangle clip = g.getClipBounds();
    g.setColor(new Color(new Random().nextInt()));
    g.fillRect(clip.x, clip.y, clip.width, clip.height);
  }
}