1 7 8 package org.jdesktop.swing; 9 10 import java.awt.Dimension ; 11 import java.awt.Image ; 12 import java.awt.Cursor ; 13 14 import java.io.File ; 15 16 import java.awt.event.MouseAdapter ; 17 import java.awt.event.MouseEvent ; 18 19 import javax.swing.BorderFactory ; 20 import javax.swing.Icon ; 21 import javax.swing.ImageIcon ; 22 import javax.swing.JFileChooser ; 23 import javax.swing.JLabel ; 24 import javax.swing.JPanel ; 25 26 import javax.swing.border.BevelBorder ; 27 28 public class JXImagePanel extends JPanel { 29 30 private JLabel imageLabel; 31 32 private String TEXT = "<html><i><b>Click on the pane<br>To set the image</b></i></html>"; 33 34 public JXImagePanel() { 35 setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); 36 37 imageLabel = new JLabel (TEXT); 38 imageLabel.setPreferredSize(new Dimension (200,200)); 39 imageLabel.addMouseListener(new MouseHandler()); 40 imageLabel.setToolTipText(TEXT); 41 add(imageLabel); 42 } 43 44 public void setIcon(Icon icon) { 45 imageLabel.setIcon(icon); 46 if (icon != null) { 47 imageLabel.setText(null); 48 } 49 else { 50 imageLabel.setText(TEXT); 51 } 52 } 53 54 public Icon getIcon() { 55 return imageLabel.getIcon(); 56 } 57 58 public void setImage(Image image) { 59 if (image != null) { 60 setIcon(new ImageIcon (image)); 61 } else { 62 setIcon(null); 63 } 64 } 65 66 public Image getImage() { 67 ImageIcon icon = (ImageIcon )imageLabel.getIcon(); 68 if (icon != null) { 69 return icon.getImage(); 70 } 71 return null; 72 } 73 74 private class MouseHandler extends MouseAdapter { 75 private Cursor oldCursor; 76 private JFileChooser chooser; 77 78 public void mouseClicked(MouseEvent evt) { 79 if (chooser == null) { 80 chooser = new JFileChooser (); 81 } 82 int retVal = chooser.showOpenDialog(JXImagePanel.this); 83 if (retVal == JFileChooser.APPROVE_OPTION) { 84 File file = chooser.getSelectedFile(); 85 try { 86 setIcon(new ImageIcon (file.toURL())); 87 } catch (Exception ex) { 88 } 89 } 90 } 91 92 public void mouseEntered(MouseEvent evt) { 93 JLabel label = (JLabel )evt.getSource(); 94 if (oldCursor == null) { 95 oldCursor = label.getCursor(); 96 label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); 97 } 98 } 99 100 public void mouseExited(MouseEvent evt) { 101 JLabel label = (JLabel )evt.getSource(); 102 if (oldCursor != null) { 103 label.setCursor(oldCursor); 104 oldCursor = null; 105 } 106 } 107 } 108 } 109 110 | Popular Tags |