Adding an image to a JLIst?
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   jelsy_joseph
Posted On:   Thursday, September 8, 2005 04:00 AM

Please tell me how can I display an image in a JList?

Re: Adding an image to a JLIst?

Posted By:   Craig_Wood  
Posted On:   Monday, September 12, 2005 03:37 PM


import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;
import javax.swing.*;

public class ImageList
{
BufferedImage[] images;
JList list;

public ImageList()
{
loadImages();
list = new JList(images);
list.setCellRenderer(new ImageRenderer());
}

private void loadImages()
{
// images from
// http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/index.html
String[] fileNames = {
"-----", "-c---", "-cg--", "-c-h-"
};
images = new BufferedImage[fileNames.length];
for(int i = 0; i < images.length; i++)
try
{
String path = "images/geek" + fileNames[i] + ".gif";
URL url = getClass().getResource(path);
images[i] = ImageIO.read(url);
}
catch(MalformedURLException mue)
{
System.out.println("url: " + mue.getMessage());
}
catch(IOException ioe)
{
System.out.println("read: " + ioe.getMessage());
}
}

public static void main(String[] args)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(new ImageList().list));
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}

class ImageRenderer extends DefaultListCellRenderer
{
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
// for default cell renderer behavior
Component c = super.getListCellRendererComponent(list, value,
index, isSelected, cellHasFocus);
// set icon for cell image
((JLabel)c).setIcon(new ImageIcon((BufferedImage)value));
((JLabel)c).setText("");
return c;
}
}

Re: Adding an image to a JLIst?

Posted By:   Almagest_FUTT  
Posted On:   Thursday, September 8, 2005 11:29 AM

javax.swing.ListCellRenderer
About | Sitemap | Contact