Tuesday, November 16, 2010

Image inside a Scroll Pane

Today I'm going to show you how you can place an image inside Scroll Pane.

  • Create new JDialog Form,


  • Drag and drop the Scroll Pane component into the JDialog Form and do the same with the JLabel (place it inside the Scoll Pane). You should have something like this,


  • Place this code inside the constructor (right after initComponents),

try {

   this.setResizable(false); //Dialog not resizable by the user
   this.setLocationRelativeTo(null); //Center form

   File f = new File("C:\\Image.jpg");

   if (f.exists()) {
      BufferedImage image = ImageIO.read(f);

      Icon imageicon = new ImageIcon(image);

      jLabel1.setText(null); //Text this component will display
      jLabel1.setIcon(imageicon); //Image that this component will display
   }


} catch (Exception e) {
   //Do something here
}


  • Import this to your project,
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;


  • Run file (Shift+F6), and you should have something like this,

And that's it.I hope that this will be a help to people. Enjoy.

No comments:

Post a Comment