Image in JScrollPane: Java Swing

  • June 4, 2010

Getting an image to properly display in a scroll pane in Java swing can be frustrating at times however its really not as difficult as we may think. To do this we create an ImageIcon, put it into a JLabel, and then put that JLabel into the JScrollPane. This can also be used to dynamically update the image if, for example, we want to play through the images. Lets look at the following code example.

import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;

public class testClass {

	private ImageIcon ii;
	private JLabel imageLabel;
	private JScrollPane scrollPane;
	public testClass() {
		//Create the JFrame to display on start
		JFrame jfrm = new JFrame();
		jfrm.setPreferredSize(new Dimension(500,500));
		//create and link the fields
		ii = new ImageIcon("someFile.gif");
		imageLabel = new JLabel(ii);
		scrollPane = new JScrollPane(imageLabel);
		//set size for the scrollPane
		scrollPane.setPreferredSize(new Dimension(400,400));
		//add scrollPane to the JFrame and make the JFrame visible
	public void changeImage(String newImageFileName) {
		//This will change the image.  We can call this function and the image shown by the scroll
		//pane will change after the function returns.
		ii = new ImageIcon(newImageFileName);
	public static void main(String[] args) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
            	testClass tc = new testClass();

No Comments

You can leave the first : )

Leave a Reply

Your email address will not be published. Required fields are marked *