How to display custom objects in JList using ListCellRenderer?

Many times we need to list items beyond just Strings, like images etc. Lets see how we can add them in a list using ListCellRenderer.
In the example below we can see we have created one class Shape, which information we want to show in the JList.
As you can see we are using DefaultListRenderer for the JList which sets the renderer for the item in a JList. We are using method getListCellRendererComponent which returns the component which has been configured to display the value, so we are getting the value as Shape. Here we are setting the text and icon of each configured object.



 
public class JListSelection {

    public static void main(String[] args){

        JFrame listDemo = new JFrame("JList Selection Disable");
        JPanel testPanel = new JPanel();
        GridBagLayout gridbagLayoutSettings = new GridBagLayout();

        testPanel.setLayout(gridbagLayoutSettings);
        // Creating Shape objects array and passing it to the JList. 

        Shape[] shapeList = {new Shape("Square", "C:\\image\\square.jpg" )
                                , new Shape("Triangle", "C:\\image\\triangle.jpg" )
                                , new Shape("Rectangle", "C:\\image\\rectangle.jpg" )};
        JList listEx = new JList(shapeList);
        listEx.setCellRenderer(new DefaultListCellRenderer() { // Setting the DefaultListCellRenderer

            public Component getListCellRendererComponent(JList list, Object value, int index,
                    boolean isSelected, boolean cellHasFocus) {
                Shape shape = ( Shape )value;  // Using value we are getting the object in JList
                setText( shape.getType() );  // Setting the text
                setIcon( shape.getImage() ); // Setting the Image Icon
                return this;
            }
        });
        JScrollPane scrollList = new JScrollPane(listEx);
        scrollList.setPreferredSize(new Dimension(250, 80));
        testPanel.add(scrollList);
        listDemo.add(testPanel);
        listDemo.setSize(300,300);
        listDemo.setVisible(true);


    }
    

}

//Shape object creation.
class Shape {

        private final String type;

        private final String imagePath;

        private ImageIcon imageIcon;

        public Shape( String typeStr, String imagePath ){
            this.type = typeStr;
            this.imagePath = imagePath;
        }
        public ImageIcon getImage() {
            if (imageIcon == null) {
              imageIcon = new ImageIcon(imagePath);
            }
            return imageIcon;
        }
        public String getType(){
            return type;
        }

    }


Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment