Java:在jscrollpanne中加载图像

时间:2016-11-11 16:49:09

标签: java swing jpanel jscrollpane

我有一些问题,我想加载图片

1类: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:选择一个图像,我尝试加载Jscrollpan(在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");
            }
        }
    }
}

主要课程

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

谢谢。

1 个答案:

答案 0 :(得分:1)

永远不要使用add(...)方法将组件添加到JScrollPane。该组件需要添加到滚动面板的JViewport

使用以下命令创建JScrollPane时会自动完成:

JScrollPane scrollPane = new JScrollPane( someComponent );

或者您可以使用:

scrollPane.setViewportView( someComponent );

如果要显示图像,则无需进行自定义绘画。只需将ImageIcon添加到JLabel并将标签添加到滚动窗格

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

如果你想做自定义绘画,那么DON&T; T扩展Canvas,这是一个AWT组件。相反,您可以扩展JPanel。当你扩展JPanel时,你需要覆盖paintComponent(...)并实现getPreferredSize(),以使滚动窗格正常工作。

阅读Custom Painting上Swing教程中的部分以获取更多信息。保留所有Swing基础知识的教程链接。

本教程还有一个关于How to Use Icons的部分,你应该阅读。