Home > other >  Is there a way to resize images when loaded? The images are linked to a JList
Is there a way to resize images when loaded? The images are linked to a JList

Time:03-19

This is the code I wrote. It works only problem I can't resize the images. I've tried out getScaledInstance wasn't working. Any ideas on how to fix this. Also, why did I have to use a container to show the pictures shouldn't the panels be enough to show the results but until I added the container I wasn't getting any outputs.

package split;

import javax.swing.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.Container;

public class Split extends JFrame implements ListSelectionListener{
   
    JFrame f;
    JSplitPane s1;
    JList list1;
    JPanel listP,ImgP;
    JLabel img;
    Container contentPane;
   
   
    String a[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};
   
    Split(){
        list1 = new JList(a);
        list1.addListSelectionListener(new ListSelectionListener(){
            @Override
            public void valueChanged(ListSelectionEvent e) {
                switch(list1.getSelectedIndex()){
                case 0:
                    img.setIcon(new ImageIcon("C:\\Users\\DELL\\Desktop\\Planets\\Mercury_profile_MDIS_MESSENGER.jpg"));
                    break;
                case 1:
                    img.setIcon(new ImageIcon("C:\\Users\\DELL\\Desktop\\Planets\\Venus_from_Mariner_10.jpg"));
                    break;
                case 2:
                    img.setIcon(new ImageIcon("C:\\Users\\DELL\\Desktop\\Planets\\download.jpg"));
                    break;
                case 3:
                    img.setIcon(new ImageIcon("C:\\Users\\DELL\\Desktop\\Planets\\download (1).jpg"));
                    break;
                case 4:
                    img.setIcon(new ImageIcon("C:\\Users\\DELL\\Desktop\\Planets\\Jupiter_and_its_shrunken_Great_Red_Spot.jpg"));
                    break;
                case 5:
                    img.setIcon(new ImageIcon("C:\\Users\\DELL\\Desktop\\Planets\\download (2).jpg"));
                    break;
                case 6:
                    img.setIcon(new ImageIcon("C:\\Users\\DELL\\Desktop\\Planets\\download (3).jpg"));
                    break;
                case 7:
                    img.setIcon(new ImageIcon("C:\\Users\\DELL\\Desktop\\Planets\\Neptune_-_Voyager_2_(29347980845)_flatten_crop.jpg"));
                    break;
                }
               
            }
       
        });
        listP = new JPanel();
        listP.add(list1);
       
        img = new JLabel();
        ImgP = new JPanel();
        ImgP.add(img);
       
        s1 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,listP, ImgP);
        s1.setOneTouchExpandable(true);
        s1.setDividerLocation(150);
        contentPane = getContentPane();
        contentPane.add(s1);
       
        setSize(500,500);
        setVisible(true);
   
       
                }

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

    @Override
    public void valueChanged(ListSelectionEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
   
}

CodePudding user response:

When using a JList, any resizing that is required can be done in the renderer. E.G. the images in the list on the left are 10% of the size of the main view when selected.

enter image description here

Here is the renderer:

class ScaledImageListCellRenderer extends DefaultListCellRenderer {

    @Override
    public Component getListCellRendererComponent(
            JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        Component c = super.getListCellRendererComponent(
                list, value, index, isSelected, cellHasFocus);

        JLabel l = (JLabel)c;
        BufferedImage bi = (BufferedImage)value;
        int w = bi.getWidth();
        int h = bi.getHeight();
        String s = w   "x"   h;
        l.setText(s);
        l.setIcon(new ImageIcon(bi.getScaledInstance(w/10, h/10, BufferedImage.SCALE_FAST)));

        return l;
    }
};

Here is the self-contained source code that uses the renderer:

import java.awt.*;
import java.awt.image.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.event.*;

public class ScaleBigImages {
    int sz = 50;
    int s = 10;
    Random random = new Random();
    JLabel imageLabel = new JLabel();

    ScaleBigImages() {
        init();
    }

    protected final void init() {
        JPanel gui = new JPanel(new BorderLayout(2,2));
        JList list = new JList();
        gui.add(new JScrollPane(list), BorderLayout.LINE_START);
        DefaultListModel dlm = new DefaultListModel();
        for (int ii=0; ii<19; ii  ) {
            dlm.addElement(getBigImage());
        }
        list.setModel(dlm);
        list.setCellRenderer(new ScaledImageListCellRenderer());
        imageLabel.setIcon(new ImageIcon(new BufferedImage(
                s*sz,s*sz, BufferedImage.TYPE_INT_ARGB)));
        JPanel center = new JPanel(new GridBagLayout());
        center.add(imageLabel);
        gui.add(center);
        ListSelectionListener lsl = new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                BufferedImage bi = (BufferedImage) list.getSelectedValue();
                imageLabel.setIcon(new ImageIcon(bi));
            }
        };
        list.addListSelectionListener(lsl);
        list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        JFrame f = new JFrame("Scale Big Images");
        f.setLocationByPlatform(true);
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.add(gui);
        f.pack();
        f.setMinimumSize(f.getSize());
        f.setVisible(true);
    }

    class ScaledImageListCellRenderer extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(
                JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            Component c = super.getListCellRendererComponent(
                    list, value, index, isSelected, cellHasFocus);

            JLabel l = (JLabel)c;
            BufferedImage bi = (BufferedImage)value;
            int w = bi.getWidth();
            int h = bi.getHeight();
            String s = w   "x"   h;
            l.setText(s);
            l.setIcon(new ImageIcon(bi.getScaledInstance(w/10, h/10, BufferedImage.SCALE_FAST)));

            return l;
        }
    };

    private BufferedImage getBigImage() {
        int w = s*sz;
        int h = s*sz;
        int r = random.nextInt(s/2);
        if (random.nextBoolean()) {
            w -= r*sz;
        } else {
            h -= r*sz;
        }

        return new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                new ScaleBigImages();
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

CodePudding user response:

I might suggest using a JScrollPane, which would allow your JLabel/image to occupy more space then is currently available to the window, for example...

enter image description here

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public final class Main {

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

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new Split();
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class Split extends JFrame {

        public Split() {
            String a[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};
            JList list1 = new JList(a);
            final JLabel img = new JLabel();
            list1.addListSelectionListener(new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) {
                        return;
                    }
                    try {
                        switch (list1.getSelectedIndex()) {
                            case 0:
                                img.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/images/Cute1.png"))));
                                break;
                            case 1:
                                img.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/images/Cute2.png"))));
                                break;
                            case 2:
                                img.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/images/Cute3.png"))));
                                break;
                            case 3:
                                img.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/images/Cute4.png"))));
                                break;
                            case 4:
                                img.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/images/Cute5.png"))));
                                break;
                            case 5:
                                img.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/images/Cute6.png"))));
                                break;
                            case 6:
                                img.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/images/Cute7.png"))));
                                break;
                            case 7:
                                img.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/images/Cute8.png"))));
                                break;
                        }
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(img, "Could not load image", "Error", JOptionPane.ERROR_MESSAGE);
                    }

                }

            });

            JPanel basePane = new JPanel(new BorderLayout()) {
                @Override
                public Dimension getPreferredSize() {
                    return new Dimension(400, 400);
                }
            };
            basePane.add(new JScrollPane(img));

            JSplitPane s1 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(list1), basePane);
            s1.setOneTouchExpandable(true);
            s1.setDividerLocation(150);

            add(s1);
        }

    }
}

See How to Use Scroll Panes for more details.

You should also learn to make use of ImageIO.read, it will save you a lot of issues and hair pulling in the long run, see Reading/Loading an Image

If you still want to resize the image, then you could also have a look at ...

as few examples

  • Related