import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.imageio.*; import java.io.*; /** * This program illustrates the display of an image stored in * a database as a Blob. **/ public class Blobber implements ActionListener { private JFrame frame; private JPanel inputPanel; private Canvas imageCanvas; private JComboBox nameBox; private Image image; private DatabaseAccess dlink; public Blobber(DatabaseAccess dlink) { this.dlink = dlink; // Set up the frame frame = new JFrame("Blob Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set up the input panel inputPanel = new JPanel(new FlowLayout()); inputPanel.setBackground(Color.LIGHT_GRAY); // Add the combo box to the input panel nameBox = new JComboBox(dlink.getCarList().toArray()); nameBox.setSelectedIndex(0); nameBox.addActionListener(this); inputPanel.add(nameBox); // Put the input panel in the frame frame.getContentPane().add(inputPanel, BorderLayout.SOUTH); // Create the image canvas and put it in the frame imageCanvas = new Canvas(){ public void paint(Graphics g){ g.drawImage(image,0,0,null); } }; imageCanvas.setSize(500,500); frame.getContentPane().add(imageCanvas, BorderLayout.CENTER); frame.pack(); // Display the frame frame.setVisible(true); } /* Listener method to handle events */ public void actionPerformed(ActionEvent e) { if (e.getSource() == nameBox) { // event came from the combo box String name = (String) nameBox.getSelectedItem(); getImage(name); imageCanvas.repaint(); } } /* retrieve the car's picture and display it */ private void getImage(String name) { InputStream imageStream = dlink.getImageStream(name); try { image = ImageIO.read(imageStream); int w = image.getWidth(frame); int h = image.getHeight(frame); imageCanvas.setSize(w,h); frame.pack(); } catch (IOException e){ warnUser(e.getMessage()); } } /** * Display a pop-up window to the user */ private void warnUser(String message) { JOptionPane.showMessageDialog(frame, message, "Error", JOptionPane.WARNING_MESSAGE); } public static void main(String [] args) { Blobber x = new Blobber(new DatabaseAccess()); } }