2

我有一个带有自定义 ListCellRenderer 的 JList,在单元格中我想添加一个从http://www.ajaxload.info/获得的加载程序 gif

问题是它不会显示 gif,有时当它显示时它不会动画。

loader.gif ->在此处输入图像描述

这里是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;
    }
}

如何显示 GIF 并为 JList 的单元格设置动画?

谢谢!

4

0 回答 0