将图像添加到 JInternalFrame 内的 JPanel

Adding Image to JPanel inside JInternalFrame

我想将图像添加到 JPanel 中,JPanel 在 JInternalFrame 中,并且 JInternalFrame 有一个父级 JDesktopPane。

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

项目首先是一个JDesptopPane,然后是一个JInternalFrame(1),从这个internalframe,它显示了另一个JInternalFrame(2),从这个internalFrame,它显示了另一个JInternalFrame(3),在internalFrame 3,我想找到一个按钮,JFileChooser,一个图像,以及文件选择器接收到的路径,我想在 Imagen() class 中设置为参数。并将图像设置为内置于 JInternalFrame(3) 中的 JPanel。

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

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);
    }  
}

此处 class 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);
    }
}

有多种方法可以做到这一点,但是,更可取的方法之一是为 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 image and Quality of Image after resize very low -- Java 了解更多详细信息和想法