如何在jlist中添加图像

时间:2014-03-08 07:33:54

标签: java swing jlist imageicon

嗨我已经创建了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();

        }
    }

我该怎么做才能帮到我?

提前致谢

1 个答案:

答案 0 :(得分:22)

您希望将其视为自定义ListCellRenderer。您可以查看JComboBox JList。对于JLabel,它也是一样的。对于简单的场景,本教程过于复杂。他们扩展implements ListCellRenderextends,如果你只想要基本的功能,那么你必须实现一些不必要的东西。

您可以改为DefaultListCellRender或创建匿名JLabel并获取Font渲染组件并添加到其中,例如设置ImageIconpublic 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; } } 。像这样的东西

getListCellRendererComponent

每个单元格都使用此渲染器并调用value方法。传递给方法的ImageIcon是每个单元格中的值,在我的例子中,是列表中的一个字符名称。然后,我将其映射到相应的Icon,并在JLabel渲染器组件上设置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(); } }); } }

enter image description here

creatAndShowGui()

旁注

  • AndrewThompson对于首先检查教程是正确的。您可以轻松找到一个示例实现,然后尝试一下。可以找到Swing教程Provding a Custom Renderer。请参阅使用Swing组件了解如何使用不同的组件。

  • Swing应用程序应该在Event Dispatch Thread(EDT)上运行。您可以将SwinUtilities.invokeLater...包裹在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(); } }); } } 中。详情请见here


使用互联网图片

更新

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

新代码

{{1}}