简体   繁体   English

如何在jlist中添加图像

[英]How to add image in jlist

Hi i have created aj 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". 嗨我已经创建了aj列表,我想在该文本中的任何文本之前添加图像我怎么能这样做我试过但我无法实现我的目标我想在列表元素“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 提前致谢

You want to look as a custom ListCellRenderer . 您希望将其视为自定义ListCellRenderer You can look at Provding a Custom Renderer for JComboBox . 您可以查看为JComboBox 提供自定义渲染器 It the same for a JList . 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. 他们扩展了JLabelimplements ListCellRender ,如果你只想要基本的功能,那么你需要实现一些不必要的东西。

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 . 你可以改为extends或创建一个匿名的DefaultListCellRender ,只需获取JLabel渲染组件并添加它,就像设置FontImageIcon 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. 会发生什么是每个单元格使用此渲染器并调用getListCellRendererComponent方法。 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. value你看到传递给方法是在每个单元格的值,在我的情况,在列表中的角色的名字之一。 I then map that to the corresponding ImageIcon and set the Icon on the JLabel renderer component. 然后,我将其映射到相应的ImageIcon并在JLabel渲染器组件上设置Icon

在此输入图像描述

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. AndrewThompson对于首先检查教程是正确的。 You could have easily found an example implementation, then tried it out. 您可以轻松找到一个示例实现,然后尝试一下。 Swing tutorials can be found here . Swing教程可以在这里找到。 Look under the Using Swing Components for how to use different components. 在使用Swing组件下查看如何使用不同的组件。

  • Swing apps should be run on the Event Dispatch Thread (EDT). Swing应用程序应该在Event Dispatch Thread(EDT)上运行。 You can do so by wrapping your creatAndShowGui() in a SwinUtilities.invokeLater... . 您可以通过将您的creatAndShowGui()包装在creatAndShowGui()中来SwinUtilities.invokeLater... See more at Initial Threads 初始线程中查看更多信息


UPDATE with internet images. 更新与互联网图像。

在此输入图像描述在此输入图像描述在此输入图像描述在此输入图像描述在此输入图像描述

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("http://i.stack.imgur.com/NCsHu.png")));
            map.put("Luigi", new ImageIcon(new URL("http://i.stack.imgur.com/UvHN4.png")));
            map.put("Bowser", new ImageIcon(new URL("http://i.stack.imgur.com/s89ON.png")));
            map.put("Koopa", new ImageIcon(new URL("http://i.stack.imgur.com/QEK2o.png")));
            map.put("Princess", new ImageIcon(new URL("http://i.stack.imgur.com/f4T4l.png")));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return map;
    }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM