Search code examples
javaswingjpaneljscrollpane

Java : load image in jscrollpanne


i have some problem whene i want to load image

1 class :Draw_Image

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;

public class Draw_Image extends Canvas{
    BufferedImage image= null;
    //Constructeur, prend une image Buffered
    public Draw_Image(BufferedImage img){
        //copier l'image dans son attribut
        image= img;
    }
    public void paint(Graphics g){
        //Peintre le graphique g d e l'image
        g.drawImage(image,0,0,this);
    }
}

2 class :choose an image and i try to loaded in Jscrollpan(declared in the Main clas)

import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JPanel;

public class LoadImage extends JPanel{
    private String path1;
    private String path2;
    private String path3;
    NewJFrame j;

    private JFileChooser parcourir= new JFileChooser();

    BufferedImage img = null;

    public LoadImage(){
        parcourir.showOpenDialog(null);
        if(parcourir.showOpenDialog(null)== JFileChooser.APPROVE_OPTION){
            //récupérer image à partir du choix de l'utilisateur
            String file2= parcourir.getSelectedFile().getPath();
            path2= file2;

            try {
                img = ImageIO.read(new File(file2));
                Draw_Image d1= new Draw_Image(img);         
                //d1.setSize(j.jScrollPane1.getWidth(),j.jScrollPane1.getHeight());

                j.jScrollPane1.removeAll();
                j. jScrollPane1.add(d1);    
                add(d1, BorderLayout.CENTER);
            }
            catch (IOException ex) {
                // Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("err");
            }
        }
    }
}

The Main class

public class Main extends javax.swing.JFrame {

/**
 * Creates new form NewJFrame
 */
public Main() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    jButton_Open_Image = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    jMenu2 = new javax.swing.JMenu();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton_Open_Image.setText("Open");
    jButton_Open_Image.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton_Open_ImageActionPerformed(evt);
        }
    });

    jButton2.setText("Gray_Scale");

    jMenu1.setText("File");
    jMenuBar1.add(jMenu1);

    jMenu2.setText("Edit");
    jMenuBar1.add(jMenu2);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jButton2)
                .addComponent(jButton_Open_Image, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
        .addGroup(layout.createSequentialGroup()
            .addGap(53, 53, 53)
            .addComponent(jButton_Open_Image)
            .addGap(18, 18, 18)
            .addComponent(jButton2)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void jButton_Open_ImageActionPerformed(java.awt.event.ActionEvent evt) {                                                   
    new LoadImage();
}                                                  

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Main().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton_Open_Image;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
protected javax.swing.JScrollPane jScrollPane1;

enter image description here

Thanks .


Solution

  • Never use the add(...) method to add a component to a JScrollPane. The component needs to be added to the JViewport of the scroll panel.

    This is done automatically when you create a JScrollPane using:

    JScrollPane scrollPane = new JScrollPane( someComponent );
    

    or you can use:

    scrollPane.setViewportView( someComponent );
    

    If you want to display an image, there is no need to do custom painting. Just add an ImageIcon to a JLabel and add the label to the scroll pane

    JLabel label = new JLabel( new ImageIcon(...) );
    JScrollPane scrollPane = new JScrollPane( label );
    

    If you do want to do custom painting the DON'T extend Canvas, that is an AWT component. Instead you can extend JPanel. When you extend JPanel you would then need to override paintComponent(...) and implement getPreferredSize() in order to get the scroll pane to work properly.

    Read the section from the Swing tutorial on Custom Painting for more information. Keep a link to the tutorial handy for all the Swing basics.

    The tutorial also has a section on How to Use Icons you should read.