Guest User

Untitled

a guest
Jul 19th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. //Test class showing the list in a frame
  2. import java.awt.Color;
  3. import java.awt.Dimension;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. import javax.swing.*;
  8. import javax.swing.border.LineBorder;
  9.  
  10.  
  11. public class Test extends JFrame{
  12.  
  13. public static void main(String[] args) {
  14.  
  15.  
  16. final JFileChooser chooser = new JFileChooser();
  17. JButton button = new JButton();
  18. button.setText("Upload");
  19. JFrame frame = new JFrame("My Frame");
  20. JList list = new JList();
  21. Map<Object, ImageIcon> icons = new HashMap<Object, ImageIcon>();
  22. list.setBorder(new LineBorder(Color.BLACK));
  23.  
  24. ImageIcon icon = new ImageIcon("/Images/400px-Greek_uc_sigma.png");
  25.  
  26. ArrayList<String> arrayList = new ArrayList<String>();
  27.  
  28. icons.put("Name", icon);
  29.  
  30. //populate the arrayList for testing
  31. arrayList.add("Smith");
  32. arrayList.add("John");
  33. arrayList.add("Bob");
  34. arrayList.add("Kim");
  35.  
  36. frame.setSize(new Dimension(400, 400));
  37. //set the list data
  38. list.setListData(arrayList.toArray());
  39. final JFrame imageFrame = new JFrame();
  40. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  41.  
  42.  
  43. list.setCellRenderer(new IconListRenderer(icons));
  44. frame.add(list);
  45. frame.setVisible(true);
  46. frame.repaint();
  47. }
  48.  
  49.  
  50.  
  51. }
  52.  
  53. import java.awt.Component;
  54. import java.util.Map;
  55. import javax.swing.DefaultListCellRenderer;
  56. import javax.swing.Icon;
  57. import javax.swing.ImageIcon;
  58. import javax.swing.JLabel;
  59. import javax.swing.JList;
  60.  
  61.  
  62. public class IconListRenderer
  63. extends DefaultListCellRenderer {
  64.  
  65. private Map<Object, ImageIcon> icons = null;
  66.  
  67. public IconListRenderer(Map<Object, ImageIcon> icons) {
  68. this.icons = icons;
  69. }
  70.  
  71. @Override
  72. public Component getListCellRendererComponent(
  73. JList list, Object value, int index,
  74. boolean isSelected, boolean cellHasFocus) {
  75.  
  76. // Get the renderer component from parent class
  77.  
  78. JLabel label =
  79. (JLabel) super.getListCellRendererComponent(list,
  80. value, index, isSelected, cellHasFocus);
  81.  
  82. // Get icon to use for the list item value
  83.  
  84. Icon icon = icons.get(value);
  85.  
  86. // Set icon to display for value
  87.  
  88. label.setIcon(icon);
  89. return label;
  90. }
  91. }
Add Comment
Please, Sign In to add comment