How to add image in jlist
Asked Answered
H

1

6

Hi i have created a j list and there i want to add an image before any text in that text how can i do this i tried but i am not able to achieve my goal i want to add an image before list element"Barmer".

    public class ListDemo extends JPanel
                          implements ListSelectionListener {
        private JList list;
        private DefaultListModel listModel;


        public ListDemo() {
            super(new BorderLayout());

            listModel = new DefaultListModel();
            listModel.addElement("Barmer");
           //Create the list and put it in a scroll pane.
            list = new JList(listModel);
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            list.setSelectedIndex(0);
            list.addListSelectionListener(this);
            list.setVisibleRowCount(5);
            list.setBackground(new java.awt.Color(0,191,255));;
           list.setFont(new Font("Arial",Font.BOLD,35));
            list.setForeground( Color.white );
            list.setFixedCellHeight(60);
    list.setFixedCellWidth(50);
    list.setBorder(new EmptyBorder(10,20, 20, 20));


            JScrollPane listScrollPane = new JScrollPane(list);
            add(listScrollPane, BorderLayout.CENTER);

        }
         public void valueChanged(ListSelectionEvent e) {

        }

        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("ListDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            //Create and set up the content pane.
            JComponent newContentPane = new ListDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
           frame.setExtendedState(JFrame.MAXIMIZED_BOTH); 
    frame.setUndecorated(true);

            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }



          public static void main(String[] args) {

                    createAndShowGUI();

        }
    }

How can i do this help me?

Thanks in advance

Horsewoman answered 8/3, 2014 at 7:33 Comment(2)
Please a) find the 'format my code' shortcut in your IDE and use it. b) Actually go through the tutorials before expecting us to spoon feed information to you. The first hit for 'jlist tutorial' shows exactly how to do it.Specimen
This question appears to be off-topic because it is about a matter easily answered by going through the official tutorial.Specimen
T
29

You want to look as a custom ListCellRenderer. You can look at Provding a Custom Renderer for JComboBox. It the same for a JList. The tutorial over-complicates a bit for simple scenarios. They extends JLabel and implements ListCellRender where you have to implement a few unnecessary things if you just want basic functionality but with am image.

You can just instead extends or create a anonymous DefaultListCellRender and just get the JLabel render component and add to it, like setting Font and ImageIcon. Something like this

public class MarioListRenderer extends DefaultListCellRenderer {

    Font font = new Font("helvitica", Font.BOLD, 24);

    @Override
    public Component getListCellRendererComponent(
            JList list, Object value, int index,
            boolean isSelected, boolean cellHasFocus) {

        JLabel label = (JLabel) super.getListCellRendererComponent(
                list, value, index, isSelected, cellHasFocus);
        label.setIcon(imageMap.get((String) value));
        label.setHorizontalTextPosition(JLabel.RIGHT);
        label.setFont(font);
        return label;
    }
}

What happens is that each cell uses this renderer and calls the getListCellRendererComponent method. The value you see passed to the method is the value in each cell, in my case, one of the character names in the list. I then map that to the corresponding ImageIcon and set the Icon on the JLabel renderer component.

enter image description here

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.util.HashMap;
import java.util.Map;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class MarioList {

    private final Map<String, ImageIcon> imageMap;

    public MarioList() {
        String[] nameList = {"Mario", "Luigi", "Bowser", "Koopa", "Princess"};
        imageMap = createImageMap(nameList);
        JList list = new JList(nameList);
        list.setCellRenderer(new MarioListRenderer());

        JScrollPane scroll = new JScrollPane(list);
        scroll.setPreferredSize(new Dimension(300, 400));

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

    public class MarioListRenderer extends DefaultListCellRenderer {

        Font font = new Font("helvitica", Font.BOLD, 24);

        @Override
        public Component getListCellRendererComponent(
                JList list, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {

            JLabel label = (JLabel) super.getListCellRendererComponent(
                    list, value, index, isSelected, cellHasFocus);
            label.setIcon(imageMap.get((String) value));
            label.setHorizontalTextPosition(JLabel.RIGHT);
            label.setFont(font);
            return label;
        }
    }

    private Map<String, ImageIcon> createImageMap(String[] list) {
        Map<String, ImageIcon> map = new HashMap<>();
        for (String s : list) {
            map.put(s, new ImageIcon(
                    getClass().getResource("/marioscaled/" + s + ".png")));
        }
        return map;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MarioList();
            }
        });
    }
}

Side Note

  • AndrewThompson is correct about just checking the tutorial first. You could have easily found an example implementation, then tried it out. Swing tutorials can be found here. Look under the Using Swing Components for how to use different components.

  • Swing apps should be run on the Event Dispatch Thread (EDT). You can do so by wrapping your creatAndShowGui() in a SwinUtilities.invokeLater.... See more at Initial Threads


UPDATE with internet images.

enter image description hereenter image description hereenter image description hereenter image description hereenter image description here

new Code

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class MarioList {

    private final Map<String, ImageIcon> imageMap;

    public MarioList() {
        String[] nameList = {"Mario", "Luigi", "Bowser", "Koopa", "Princess"};
        imageMap = createImageMap(nameList);
        JList list = new JList(nameList);
        list.setCellRenderer(new MarioListRenderer());

        JScrollPane scroll = new JScrollPane(list);
        scroll.setPreferredSize(new Dimension(300, 400));

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

    public class MarioListRenderer extends DefaultListCellRenderer {

        Font font = new Font("helvitica", Font.BOLD, 24);

        @Override
        public Component getListCellRendererComponent(
                JList list, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {

            JLabel label = (JLabel) super.getListCellRendererComponent(
                    list, value, index, isSelected, cellHasFocus);
            label.setIcon(imageMap.get((String) value));
            label.setHorizontalTextPosition(JLabel.RIGHT);
            label.setFont(font);
            return label;
        }
    }

    private Map<String, ImageIcon> createImageMap(String[] list) {
        Map<String, ImageIcon> map = new HashMap<>();
        try {
            map.put("Mario", new ImageIcon(new URL("https://i.sstatic.net/NCsHu.png")));
            map.put("Luigi", new ImageIcon(new URL("https://i.sstatic.net/UvHN4.png")));
            map.put("Bowser", new ImageIcon(new URL("https://i.sstatic.net/s89ON.png")));
            map.put("Koopa", new ImageIcon(new URL("https://i.sstatic.net/QEK2o.png")));
            map.put("Princess", new ImageIcon(new URL("https://i.sstatic.net/f4T4l.png")));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return map;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MarioList();
            }
        });
    }
}
Tresatrescha answered 8/3, 2014 at 8:24 Comment(14)
dear i am compiling your program giving exceptionHorsewoman
You need to use your own images, My images paths will not work for you.Tresatrescha
Hold on, I will fix it, so you can use the same images from the internetTresatrescha
i am using my image path E:\\SOFTWARE\\TrainPIS\\res\\drawable in plce of /marioscaled/Horsewoman
That's not an embeded resources path, so you cant use getClass().getResource()Tresatrescha
Try out the new code. Also look at how to use embedded-resourcesTresatrescha
i want to set word Mario on the topHorsewoman
If you want it on top of the image, just use label.setVerticalTextPosition(JLabel.TOP); label.setHorizontalTextPosition(JLabel.CENTER);Tresatrescha
Thanks it work but now i am trying to draw line between every image so nothing is drawing over thereHorsewoman
I don't get what you mean?Tresatrescha
between every image i want to draw a line i updated where my codeHorsewoman
Try this label.setBorder(new MatteBorder( 0, 0, 1, 0, Color.GRAY));Tresatrescha
after mario shoukd draw a line then after luigi should draw a line .... like this i wantHorsewoman
let us continue this discussion in chatHorsewoman

© 2022 - 2024 — McMap. All rights reserved.