How to create JList with icon and text?
Asked Answered
C

1

12

I have this code want to make JList talk text and icon what must to do.
Some persons advice me to make list of label and in table put text an icon is it Possible? How?

Search on ///////////////// for embedded comment.

import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.filechooser.FileSystemView;

public class pan extends JPanel implements DropTargetListener {

private DefaultListModel listModel = new DefaultListModel();
private DropTarget dropTarget;
private JLabel jLabel1;
private JScrollPane jScrollPane1;
private JList list;

/**
 * Create the panel.
 */
public pan() {
    setLayout(null);        
    list = new JList();
    dropTarget = new DropTarget(list, this);
    list.setModel(listModel);
    list.setDragEnabled(true);
    //list.setTransferHandler(new FileTransferHandler());
    jScrollPane1 = new JScrollPane();

    jScrollPane1.setViewportView(list);
    jScrollPane1.setBounds(10, 150, 635, 330);
    add(jScrollPane1);

}
public void dragEnter(DropTargetDragEvent arg0) {
    // nothing
}

public void dragOver(DropTargetDragEvent arg0) {
    // nothing
}

public void dropActionChanged(DropTargetDragEvent arg0) {
    // nothing
}

public void dragExit(DropTargetEvent arg0) {
    // nothing
}

public void drop(DropTargetDropEvent evt) {
    int action = evt.getDropAction();
    evt.acceptDrop(action);
    try {
        Transferable data = evt.getTransferable();
        if (data.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
              List<File> files = (List<File>) data.getTransferDat(DataFlavor.javaFileListFlavor);
            for (File file : files) {

    Icon icon=FileSystemView.getFileSystemView().getSystemIcon(file);
/////////////////listModel.addElement(filepath+icon);///////////////////////want code do this

            }
        }
    } catch (UnsupportedFlavorException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        evt.dropComplete(true);
    }
 }

}

After solve this problem i will add action to each element if doubel click on it will open desktop
to path stored in list.

Cinematography answered 11/11, 2012 at 23:57 Comment(1)
See How to Use Lists: Writing a Custom Cell Renderer.Handicraftsman
H
15

FileDragList

import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.util.List;

public class FileDropList extends JPanel implements DropTargetListener {

    private DefaultListModel listModel = new DefaultListModel();
    private DropTarget dropTarget;
    private JLabel jLabel1;
    private JScrollPane jScrollPane1;
    private JList list;

    /**
     * Create the panel.
     */
    public FileDropList() {
        //setLayout(null);        
        list = new JList();
        dropTarget = new DropTarget(list, this);
        list.setModel(listModel);
        list.setDragEnabled(true);
        FileListCellRenderer renderer = new FileListCellRenderer();
        list.setCellRenderer(renderer);
        //list.setTransferHandler(new FileTransferHandler());
        jScrollPane1 = new JScrollPane(list);

        //jScrollPane1.setBounds(10, 150, 635, 330);
        add(jScrollPane1);

    }
    public static void main(String[] args) throws Exception {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JPanel pan = new FileDropList();
                pan.setBorder(new LineBorder(Color.BLACK));
                JOptionPane.showMessageDialog(null, pan);
            }
        };
        SwingUtilities.invokeLater(r);
    }

    public void dragEnter(DropTargetDragEvent arg0) {
        // nothing
    }

    public void dragOver(DropTargetDragEvent arg0) {
        // nothing
    }

    public void dropActionChanged(DropTargetDragEvent arg0) {
        // nothing
    }

    public void dragExit(DropTargetEvent arg0) {
        // nothing
    }

    public void drop(DropTargetDropEvent evt) {
        int action = evt.getDropAction();
        evt.acceptDrop(action);
        try {
            Transferable data = evt.getTransferable();
            if (data.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                List<File> files = (List<File>) data.getTransferData(DataFlavor.javaFileListFlavor);
                for (File file : files) {
                    listModel.addElement(file);
                }
            }
        } catch (UnsupportedFlavorException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            evt.dropComplete(true);
        }
    }
}

/** A FileListCellRenderer for a File. */
class FileListCellRenderer extends DefaultListCellRenderer {

    private static final long serialVersionUID = -7799441088157759804L;
    private FileSystemView fileSystemView;
    private JLabel label;
    private Color textSelectionColor = Color.BLACK;
    private Color backgroundSelectionColor = Color.CYAN;
    private Color textNonSelectionColor = Color.BLACK;
    private Color backgroundNonSelectionColor = Color.WHITE;

    FileListCellRenderer() {
        label = new JLabel();
        label.setOpaque(true);
        fileSystemView = FileSystemView.getFileSystemView();
    }

    @Override
    public Component getListCellRendererComponent(
            JList list,
            Object value,
            int index,
            boolean selected,
            boolean expanded) {

        File file = (File)value;
        label.setIcon(fileSystemView.getSystemIcon(file));
        label.setText(fileSystemView.getSystemDisplayName(file));
        label.setToolTipText(file.getPath());

        if (selected) {
            label.setBackground(backgroundSelectionColor);
            label.setForeground(textSelectionColor);
        } else {
            label.setBackground(backgroundNonSelectionColor);
            label.setForeground(textNonSelectionColor);
        }

        return label;
    }
}

Original Answer

import java.awt.datatransfer.*;
import java.awt.dnd.*;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.util.List;

public class FileDragList extends JPanel implements DropTargetListener {

    private static final long serialVersionUID = 1L;
    private DefaultListModel listModel = new DefaultListModel();
    private JScrollPane jScrollPane1;
    private JList list;

    /**
     * Create the panel.
     */
    public FileDragList() {
        setLayout(null);        
        list = new JList();
        DropTarget dropTarget = new DropTarget(list, this);
        list.setModel(listModel);
        list.setDragEnabled(true);
        FileListCellRenderer renderer = new FileListCellRenderer();
        list.setCellRenderer(renderer);
        //list.setTransferHandler(new FileTransferHandler());
        jScrollPane1 = new JScrollPane();

        jScrollPane1.setViewportView(list);
        jScrollPane1.setBounds(10, 150, 635, 330);
        add(jScrollPane1);

    }
    public static void main(String[] args) throws Exception {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JOptionPane.showMessageDialog(null, new FileDragList());
            }
        };
        SwingUtilities.invokeLater(r);
    }

    public void dragEnter(DropTargetDragEvent arg0) {
        // nothing
    }

    public void dragOver(DropTargetDragEvent arg0) {
        // nothing
    }

    public void dropActionChanged(DropTargetDragEvent arg0) {
        // nothing
    }

    public void dragExit(DropTargetEvent arg0) {
        // nothing
    }

    public void drop(DropTargetDropEvent evt) {
        int action = evt.getDropAction();
        evt.acceptDrop(action);
        try {
            Transferable data = evt.getTransferable();
            if (data.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                List<File> files = (List<File>) data.getTransferData(DataFlavor.javaFileListFlavor);
                for (File file : files) {

                    Icon icon=FileSystemView.getFileSystemView().getSystemIcon(file);
                    /////////////////listModel.addElement(filepath+icon);///////////////////////want code do this

                }
            }
        } catch (UnsupportedFlavorException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            evt.dropComplete(true);
        }
    }
}

Icon icon=FileSystemView.getFileSystemView().getSystemIcon(file);

Oh right.. Try a variant of the FileTreeCellRenderer of File Browser GUI.

That's it, used for the tree on the left.

FileTreeCellRenderer

/** A TreeCellRenderer for a File. */
class FileTreeCellRenderer extends DefaultTreeCellRenderer {

    private FileSystemView fileSystemView;
    private JLabel label;

    FileTreeCellRenderer() {
        label = new JLabel();
        label.setOpaque(true);
        fileSystemView = FileSystemView.getFileSystemView();
    }

    @Override
    public Component getTreeCellRendererComponent(
        JTree tree,
        Object value,
        boolean selected,
        boolean expanded,
        boolean leaf,
        int row,
        boolean hasFocus) {

        DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
        File file = (File)node.getUserObject();
        label.setIcon(fileSystemView.getSystemIcon(file));
        label.setText(fileSystemView.getSystemDisplayName(file));
        label.setToolTipText(file.getPath());

        if (selected) {
            label.setBackground(backgroundSelectionColor);
            label.setForeground(textSelectionColor);
        } else {
            label.setBackground(backgroundNonSelectionColor);
            label.setForeground(textNonSelectionColor);
        }

        return label;
    }
}

Update

An SSCCE that adapts the renderer above for lists.

enter image description here

import java.awt.*;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.io.File;

public class FileList {
    public static void main(String[] args) throws Exception {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JPanel gui = new JPanel(new BorderLayout(2,2));

                File userHome = new File(System.getProperty("user.home"));
                File[] files = userHome.listFiles();
                JList list = new JList(files);
                list.setCellRenderer(new FileListCellRenderer());
                gui.add(new JScrollPane(list));

                JOptionPane.showMessageDialog(null, gui);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

/** A FileListCellRenderer for a File. */
class FileListCellRenderer extends DefaultListCellRenderer {

    private static final long serialVersionUID = -7799441088157759804L;
    private FileSystemView fileSystemView;
    private JLabel label;
    private Color textSelectionColor = Color.BLACK;
    private Color backgroundSelectionColor = Color.CYAN;
    private Color textNonSelectionColor = Color.BLACK;
    private Color backgroundNonSelectionColor = Color.WHITE;

    FileListCellRenderer() {
        label = new JLabel();
        label.setOpaque(true);
        fileSystemView = FileSystemView.getFileSystemView();
    }

    @Override
    public Component getListCellRendererComponent(
        JList list,
        Object value,
        int index,
        boolean selected,
        boolean expanded) {

        File file = (File)value;
        label.setIcon(fileSystemView.getSystemIcon(file));
        label.setText(fileSystemView.getSystemDisplayName(file));
        label.setToolTipText(file.getPath());

        if (selected) {
            label.setBackground(backgroundSelectionColor);
            label.setForeground(textSelectionColor);
        } else {
            label.setBackground(backgroundNonSelectionColor);
            label.setForeground(textNonSelectionColor);
        }

        return label;
    }
}
Handicraftsman answered 12/11, 2012 at 0:13 Comment(1)
Your FileListCellRenderer does a lot, where mainly an icon needs to be managed with the item and to be set in the DefaultListCellRenderer subclass. The actual rendering of the icon is built-in.Dysphoria

© 2022 - 2024 — McMap. All rights reserved.