1  import java.sql.*;
  2  import java.io.*;
  3  import javafx.application.Application;
  4  import javafx.scene.Scene;
  5  import javafx.scene.control.ComboBox;
  6  import javafx.scene.control.Label;
  7  import javafx.scene.image.Image;
  8  import javafx.scene.image.ImageView;
  9  import javafx.scene.layout.BorderPane;
 10  import javafx.stage.Stage;
 11  
 12  public class StoreAndRetrieveImage extends Application {
 13    // Connection to the database
 14    private Connection connection;
 15  
 16    // Statement for static SQL statements
 17    private Statement stmt;
 18  
 19    // Prepared statement
 20    private PreparedStatement pstmt = null;
 21    private DescriptionPane descriptionPane
 22      = new DescriptionPane();
 23  
 24    private ComboBox<String> cboCountry = new ComboBox<>();
 25  
 26    @Override // Override the start method in the Application class
 27    public void start(Stage primaryStage) {
 28      try {
 29        connectDB(); // Connect to DB
 30        storeDataToTable(); //Store data to the table (including image)
 31        fillDataInComboBox(); // Fill in combo box
 32        retrieveFlagInfo(cboCountry.getSelectionModel().getSelectedItem());
 33      }
 34      catch (Exception ex) {
 35        ex.printStackTrace();
 36      }
 37  
 38      BorderPane paneForComboBox = new BorderPane();
 39      paneForComboBox.setLeft(new Label("Select a country: "));
 40      paneForComboBox.setCenter(cboCountry);
 41      cboCountry.setPrefWidth(400);
 42      BorderPane pane = new BorderPane();
 43      pane.setTop(paneForComboBox);
 44      pane.setCenter(descriptionPane);
 45      
 46      Scene scene = new Scene(pane, 350, 150);
 47      primaryStage.setTitle("StoreAndRetrieveImage"); 
 48      primaryStage.setScene(scene); // Place the scene in the stage
 49      primaryStage.show(); // Display the stage
 50      
 51      cboCountry.setOnAction(e ->
 52        retrieveFlagInfo(cboCountry.getValue()));
 53    }
 54  
 55    private void connectDB() throws Exception {
 56      // Load the driver
 57      Class.forName("com.mysql.jdbc.Driver");
 58      System.out.println("Driver loaded");
 59  
 60      // Establish connection
 61      connection = DriverManager.getConnection
 62        ("jdbc:mysql://localhost/javabook", "scott", "tiger");
 63      System.out.println("Database connected");
 64  
 65      // Create a statement for static SQL
 66      stmt = connection.createStatement();
 67  
 68      // Create a prepared statement to retrieve flag and description
 69      pstmt = connection.prepareStatement("select flag, description " +
 70        "from Country where name = ?");
 71    }
 72  
 73    private void storeDataToTable() {
 74      String[] countries = {"Canada", "UK", "USA", "Germany",
 75        "Indian", "China"};
 76  
 77      String[] imageFilenames = {"image/ca.gif", "image/uk.gif",
 78        "image/us.gif", "image/germany.gif", "image/india.gif",
 79        "image/china.gif"};
 80  
 81      String[] descriptions = {"A text to describe Canadian " +
 82        "flag is omitted", "British flag ...", "American flag ...",
 83        "German flag ...", "Indian flag ...", "Chinese flag ..."};
 84  
 85      try {
 86        // Create a prepared statement to insert records
 87        PreparedStatement pstmt = connection.prepareStatement(
 88          "insert into Country values(?, ?, ?)");
 89  
 90        // Store all predefined records
 91        for (int i = 0; i < countries.length; i++) {
 92          pstmt.setString(1, countries[i]);
 93  
 94          // Store image to the table cell
 95          java.net.URL url =
 96            this.getClass().getResource(imageFilenames[i]);
 97          InputStream inputImage = url.openStream();
 98          pstmt.setBinaryStream(2, inputImage,
 99            (int)(inputImage.available()));
100  
101          pstmt.setString(3, descriptions[i]);
102          pstmt.executeUpdate();
103        }
104  
105        System.out.println("Table Country populated");
106      }
107      catch (Exception ex) {
108        ex.printStackTrace();
109      }
110    }
111  
112    private void fillDataInComboBox() throws Exception {
113      ResultSet rs = stmt.executeQuery("select name from Country");
114      while (rs.next()) {
115        cboCountry.getItems().add(rs.getString(1));
116      }
117      cboCountry.getSelectionModel().selectFirst();
118    }
119  
120    private void retrieveFlagInfo(String name) {
121      try {
122        pstmt.setString(1, name);
123        ResultSet rs = pstmt.executeQuery();
124        if (rs.next()) {
125          Blob blob = rs.getBlob(1);     
126          ByteArrayInputStream in = new ByteArrayInputStream
127            (blob.getBytes(1, (int)blob.length()));
128          Image image = new Image(in);
129          ImageView imageView = new ImageView(image);
130          descriptionPane.setImageView(imageView);
131          descriptionPane.setTitle(name);
132          String description = rs.getString(2);
133          descriptionPane.setDescription(description);
134        }
135      }
136      catch (Exception ex) {
137        System.err.println(ex);
138      }
139    }
140    
141    /**
142     * The main method is only needed for the IDE with limited
143     * avaFX support. Not needed for running from the command line.
144     */
145    public static void main(String[] args) { 
146      launch(args);
147    }
148  }