2

I have a JList with Custom ListCellRenderer, In the Cell I would like to add a loader gif I got from http://www.ajaxload.info/

The problem is it won't show the gif and sometimes when it shows it won't animate it.

loader.gif -> enter image description here

Here is SSCCE

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

private static final String hireString = "Hire";
private static final String fireString = "Fire";
private JButton fireButton;
private JTextField employeeName;

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

    listModel = new DefaultListModel();
    listModel.addElement("Jane Doe");
    listModel.addElement("John Smith");
    listModel.addElement("Kathy Green");

    //Create the list and put it in a scroll pane.
    list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setSelectedIndex(0);
    list.setVisibleRowCount(5);
    list.setCellRenderer(new MyListCellRenderer());
    JScrollPane listScrollPane = new JScrollPane(list);

    add(listScrollPane, BorderLayout.CENTER);
}


/**
 * Create the GUI and show it.  For thread safety,
 * this method should be invoked from the
 * event-dispatching thread.
 */
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);

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

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

static class MyListCellRenderer extends JPanel implements ListCellRenderer{

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        removeAll();
        ImageIcon loading = new ImageIcon(AjaxLoad.class.getResource("/sample/loader.gif"));
        add(new JLabel("Loading: "), JLabel.CENTER);
        add(new JLabel(loading), JLabel.CENTER);
        setBorder(isSelected ? BorderFactory.createLineBorder(Color.BLUE, 1) : BorderFactory.createEmptyBorder(1, 1, 1, 1));
        return this;
    }
}

How can I display a GIF and animate it for the cells of JList?

Thank you!

Mo3z
  • 2,138
  • 7
  • 21
  • 29
  • 1
    `JList` uses (almost) the same mechanism as `JTable`. Hence, see [this](http://stackoverflow.com/questions/575782/how-to-display-animation-in-a-jtable-cell) – Ordous May 19 '15 at 16:59

0 Answers0