将图像添加到JInternalFrame中的JPanel

时间:2015-05-19 00:01:57

标签: java image swing jinternalframe jdesktoppane

我想在JPanel中添加一个Image,JPanel在JInternalFrame中,而JInternalFrame有一个父JDesktopPane。

我尝试过另一个类从路径添加一个Image,然后,jPanel1 = new Imagen(<String FilePath>);,该类将在窗口构造函数中接收String中的路径,但它不起作用。我尝试通过自定义initComponents(),行jPanel1 = javax.swing.JPanel();中的代码并用jPanel1 = new Imagen()替换此行,构造函数将接收的参数是图像文件的路径,这个方法工作正常,但它只运行一次(在initComponents()方法内),我不能(或者我不知道)如何从JPanel替换图像。 :(

项目首先使用JDesptopPane,然后是一个JInternalFrame(1),从这个内部框架,它显示其他JInternalFrame(2),从这个internalFrame,它显示其他JInternalFrame(3),在internalFrame 3中,我想要要找到一个按钮,JFileChooser,一个图像,以及filechooser接收的路径,我想在Imagen()类中设置为参数。并将图像设置为构建到JInternalFrame(3)中的JPanel。

编辑1:感谢您的评论。这里是JInternalFrame(3)的代码,窗口构造函数:

public AgregarContacto() {

    JFileChooser jf = new JFileChooser();

    jf.setDialogTitle("Elija el archivo de Imagen");
    int i = jf.showOpenDialog(null);

    if (i == JFileChooser.APPROVE_OPTION) {

        default1 = jf.getSelectedFile().getAbsolutePath();
    }
    initComponents();
    jPanel1= new Imagen(default1);
    for (String llenarMese : p.llenarMeses()) {
        Mes.addItem(llenarMese);
    }

    for (String llenarDia : p.llenarDias31()) {
        Dia.addItem(llenarDia);
    }

    for (String llenarAnios : p.Anios()) {
        Anio.addItem(llenarAnios);
    }  
}

这里是Imagen()类的代码,它将在构造函数中接收一个字符串:

public class Imagen extends JPanel {
    String ruta;
    private BufferedImage imag;

    public Imagen(String path){
        ruta = path;
        try{
            imag = ImageIO.read(new File("unknown.png"));
        }catch(IOException ex){
            JOptionPane.showMessageDialog(null, "Error " + ex.getMessage());
        }
    }


    @Override
    public void paint(Graphics g){
    super.paint(g);
    Image Scaledimage = imag.getScaledInstance(this.getWidth(), this.getHeight(), Image.SCALE_SMOOTH);
    g.drawImage(Scaledimage, 0, 0, null);
    }
}

1 个答案:

答案 0 :(得分:2)

有很多方法可以做到这一点,但是,更优选的一种方法是让ImagePane能够更改正在显示的图像而无需创建它的新实例

通过这种方式,您只需将ImagePane引用传递给您要加载的图片,然后让它完成工作

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileFilter;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JDesktopPane dp = new JDesktopPane() {
                    @Override
                    public Dimension getPreferredSize() {
                        return new Dimension(600, 600);
                    }
                };

                JInternalFrame inFrm = new JInternalFrame("Image", true, true, true, true);
                inFrm.add(new ShowImagePane());
                inFrm.pack();
                inFrm.setVisible(true);
                dp.add(inFrm);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(dp);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ShowImagePane extends JPanel {

        private JFileChooser fc;

        public ShowImagePane() {
            setLayout(new BorderLayout());
            ImagePane imagePane = new ImagePane();
            add(imagePane);
            JButton open = new JButton("Open...");
            open.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (fc == null) {
                        fc = new JFileChooser();
                        fc.addChoosableFileFilter(new FileFilter() {

                            @Override
                            public boolean accept(File f) {
                                String name = f.getName().toLowerCase();
                                return name.endsWith(".png")
                                                || name.endsWith(".jpg")
                                                || name.endsWith(".jpeg")
                                                || name.endsWith(".bmp");
                            }

                            @Override
                            public String getDescription() {
                                return "Images";
                            }
                        });
                        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                        fc.setMultiSelectionEnabled(false);
                    }

                    switch (fc.showOpenDialog(ShowImagePane.this)) {
                        case JFileChooser.APPROVE_OPTION:
                            File selected = fc.getSelectedFile();
                            try {
                                imagePane.setImageSource(selected);
                            } catch (IOException ex) {
                                ex.printStackTrace();
                            }
                            break;
                    }
                }
            });
            add(open, BorderLayout.SOUTH);
        }

    }

    public class ImagePane extends JPanel {

        private BufferedImage bgImage;
        private Image scaled;

        public ImagePane(File source) throws IOException {
            setImageSource(source);
        }

        public ImagePane() {
        }

        @Override
        public void invalidate() {
            super.invalidate();
            resizeImage();
        }

        public void setImageSource(File source) throws IOException {
            if (source != null) {
                bgImage = ImageIO.read(source);
                resizeImage();
            } else {
                bgImage = null;
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return bgImage == null ? new Dimension(200, 200) : new Dimension(bgImage.getWidth(), bgImage.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (scaled != null) {
                Graphics2D g2d = (Graphics2D) g.create();
                int x = (getWidth() - scaled.getWidth(this)) / 2;
                int y = (getHeight() - scaled.getHeight(this)) / 2;
                g2d.drawImage(scaled, x, y, this);
                g2d.dispose();
            }
        }

        protected void resizeImage() {
            if (bgImage != null) {
                if (getWidth() < getHeight()) {
                    scaled = bgImage.getScaledInstance(this.getWidth(), -1, Image.SCALE_SMOOTH);
                } else {
                    scaled = bgImage.getScaledInstance(-1, getHeight(), Image.SCALE_SMOOTH);
                }
                repaint();
            }
        }

    }

}

Image#getScaledInstance既不是最快,也不是最重要的最佳质量缩放算法。因为重新缩放图像需要花费一些时间,所以只有在必要时才应该这样做。

请查看Java: maintaining aspect ratio of JPanel background imageQuality of Image after resize very low -- Java了解更多详情和想法