View Single Post
  #3 (permalink)  
Old 06-03-2008, 05:59 AM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,222
hardwired is on a distinguished road
Images from Using Swing Components Examples.
Code:
import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.event.*; public class StoreTest implements ListSelectionListener { ImageStore[] stores; JList list; JLabel imageLabel; JLabel nameLabel; ImageIcon icon; public StoreTest(BufferedImage[] images) { String[] names = { "chin", "glasses", "hat", "teeth" }; stores = new ImageStore[images.length]; for(int i = 0; i < stores.length; i++) { stores[i] = new ImageStore(images[i], names[i]); } } public void valueChanged(ListSelectionEvent e) { if(!e.getValueIsAdjusting()) { int index = list.getSelectedIndex(); BufferedImage image = stores[index].image; icon.setImage(image); imageLabel.repaint(); nameLabel.setText(stores[index].name); nameLabel.repaint(); } } private JPanel getContent() { JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.weightx = 1.0; panel.add(getList(), gbc); panel.add(getLabelPanel(), gbc); return panel; } private JList getList() { DefaultListModel model = new DefaultListModel(); for(int i = 0; i < stores.length; i++) { model.addElement(stores[i]); // toString method called } list = new JList(model); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.addListSelectionListener(this); return list; } private JPanel getLabelPanel() { icon = new ImageIcon(stores[0].image); imageLabel = new JLabel(icon, JLabel.CENTER); nameLabel = new JLabel(stores[0].name, JLabel.CENTER); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; panel.add(imageLabel, gbc); panel.add(nameLabel, gbc); return panel; } public static void main(String[] args) throws IOException { String[] ids = { "-c---", "--g--", "---h-", "----t" }; String prefix = "images/geek/geek"; String ext = ".gif"; BufferedImage[] images = new BufferedImage[ids.length]; for(int i = 0; i < images.length; i++) { String path = prefix + ids[i] + ext; images[i] = ImageIO.read(new File(path)); } StoreTest test = new StoreTest(images); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(test.getContent()); f.setSize(400,400); f.setLocation(200,200); f.setVisible(true); } } class ImageStore { BufferedImage image; String name; public ImageStore(BufferedImage image, String name) { this.image = image; this.name = name; } public String toString() { return name; } }
Reply With Quote