JDBC JTable image - java

I have an item database (jdbc) the functionality is: insert, delete, and update using GUI JTable, all work good but I need to display the image in the JTable but I couldn't :(
If you could help me in that, here's the code for the main functionality:
fill Table method:
try{
connection= DriverManager.getConnection(url, usr, pas);
statement = connection.createStatement();
resultSet = statement.executeQuery("select * from item");
itemTable.setModel(DbUtils.resultSetToTableModel(resultSet));
} catch(SQLException ex){
JOptionPane.showMessageDialog(null, ex);}
add method:
try{
PreparedStatement insert =connection.prepareStatement("INSERT INTO items"
+"(name, price, image, ID)"
+"VALUES(?,?,?,?)");
insert.setString(1, nameTextField.getText());
insert.setDouble(2, Double.parseDouble(priceTextField.getText()));
insert.setByte(3, image);
insert.setInt(4, Integer.parseInt(IDTextField.getText()));
int row = insert.executeUpdate();
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
update method:
try{
PreparedStatement update =connection.prepareStatement("update item set "
+ "name=? , price=?, image=? where id=?""
+"VALUES(?,?,?,?)");
update.setString(1, nameTextField.getText());
update.setDouble(2, Double.parseDouble(priceTextField.getText()));
update.setByte(3, image);
update.setInt(4, Integer.parseInt(IDTextField.getText()));
int row = update.executeUpdate();
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
delete method:
try{
Statement delete = connection.createStatement();
delete.executeUpdate("delete from item where id="+IDTextField.getText());
priceTextField.setText("");
nameTextField.setText("");
idTextField.setText("");
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
A button event to choose image from JFileChooser:
String imagePath = null;
JFileChooser file;
private void ChooseImageButtonActionPerformed(java.awt.event.ActionEvent evt){
int result = file.showSaveDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
File selectedFile = file.getSelectedFile();
String path = selectedFile.getAbsolutePath();
imagePath = path;
}
}

The important methods are fillTable() and add().
fillTable method could be like this:
//you need a TableModel, let´s call it model and let´s call your JTable myJTable
TableModel model = (javax.swing.table.DefaultTableModel) myJTable.getModel();
myJTable.setModel(model);
//try to add results
try {
connection = DriverManager.getConnection(url, usr, pas);
statement = connection.createStatement();
resultSet = statement.executeQuery("select * from item");
while (resultSet.next()) {
//after your query, get the Image
Blob blob = resultSet.getBlob(3);//column 3
byte[] data = blob.getBytes(1, (int) blob.length());
BufferedImage img = null;
img = ImageIO.read(new ByteArrayInputStream(data));
Icon imgToTable = imageToIcon(img);//use the method below
//add row to your table (throught the model)
model.addRow(new Object[]{resultSet.getObject(1).toString(), resultSet.getObject(2).toString(), imgToTable,resultSet.getObject(4).toString()});
//itemTable.setModel(DbUtils.resultSetToTableModel(resultSet));
}
resultSet.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
Add method could be like this:
try{
PreparedStatement insert =connection.prepareStatement("INSERT INTO items"
+"(name, price, image, ID)"
+"VALUES(?,?,?,?)");
insert.setString(1, nameTextField.getText());
insert.setDouble(2, Double.parseDouble(priceTextField.getText()));
//i recommend to use something like this to configure you image
file = new File(imagePath);
fis = new FileInputStream(file);
if (null == fis) {
fis = new FileInputStream(imagePath);
}
//configure image
insert.setBinaryStream(3, fis);
// insert.setByte(3, image);
insert.setInt(4, Integer.parseInt(IDTextField.getText()));
int row = insert.executeUpdate();
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
And use this to convert from Image to Icon (to put it in a Table Cell):
//from Image a Icon
public Icon imageToIcon(Image image) {
ImageIcon imgIcon = new ImageIcon(image);
Icon iconReturn = (Icon) imgIcon;
return iconReturn;
}
If in your database you are not using blob let me know.

Related

How to remove a row from mysql data base using JTable?

How can I remove a row from database using Mysql database using JTable. What I'm trying to do is when user select the row and click delete button I want to delete that row from data base.
private void deleteItemBtn1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
try{
if(jTable2.getSelectedRowCount()== 1){
int SelectedRowIndex = jTable2.getSelectedRow();
int row = jTable2.getSelectedRow();
String eve = model.getValueAt(row, 4).toString();
expenseDAO.deleteRow(eve);
model.removeRow(SelectedRowIndex);
}else{
if(jTable2.getRowCount()==0){
JOptionPane.showMessageDialog(this,"Table is Empty");
}else{
JOptionPane.showMessageDialog(this,"Please slelect s ingle row for Delete");
}
}
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
This is my deleteRow method :
public void deleteRow(String value){
String query = "DELETE FROM expense WHERE ex_id ="+value;
Statement st;
try {
st = con.createStatement();
st.executeQuery(query);
} catch (SQLException ex) {
Logger.getLogger(ExpenseDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
This code not working.

Image not visible in JLabel with mouse click in JTable

I'm making a small application for a school project. Inserting photos into SQL database is fine, I rename the photos in a JTable and can also open blob photos in SQL editor. It is not possible to make the photos visible on a JLabel.
Can someone help me on this?
The intention is to get a preview of the information that has been entered at a mouse click. the application is an image bank where you can enter different healthcare devices.
Code JTable
DefaultTableModel model = (DefaultTableModel) tableDom.getModel();
try {
Class.forName("com.mysql.jdbc.Driver"); //database connectie maken
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybrains?
allowMultiQueries=true&serverTimezone=America/Winnipeg&dummyparam=", "", "")) {
String sql = "Select * from Telefonie ";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery(sql);
model.setRowCount(0);
while (rs.next()) {
int id = rs.getInt("ID");
String naam = rs.getString("naam"); // naam is een kollom in de database
String model_type = rs.getString("Model_Type");
String functionaliteit = rs.getString("Functionaliteit");
String troubleshoot = rs.getString("Troubleshoot");
String oplossing = rs.getString("Oplossing");
String voorbeeld = rs.getString("Fotonaam");
byte[] fotos = rs.getBytes("Uploadfoto");
// ImageIcon imageicon = new ImageIcon(fotos);
//voorbeeldfoto.setIcon(imageicon);
//voorbeeldfoto.setIcon(foto());
model.addRow(new Object[]{id, naam, model_type, functionaliteit, troubleshoot,
oplossing, voorbeeld, fotos});
}
}
} catch (ClassNotFoundException | SQLException e) {
}
Code Mouse Clicked
try {
int i = tableDom.getSelectedRow();
Class.forName("com.mysql.jdbc.Driver"); //database connectie maken
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybrains?
allowMultiQueries=true&serverTimezone=America/Winnipeg&dummyparam=", "", "");
String sql = "Select * from Telefonie";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery(sql);
if (rs.next());
//int i = tableDom.getSelectedRow();
TableModel model = tableDom.getModel();
iD.setText(model.getValueAt(i, 0).toString());
name.setText(model.getValueAt(i, 1).toString());
modelt.setText(model.getValueAt(i, 2).toString());
func.setText(model.getValueAt(i, 3).toString());
oplos.setText(model.getValueAt(i, 4).toString());
troubl.setText(model.getValueAt(i, 5).toString());
photoNaam.setText(model.getValueAt(i, 6).toString());
byte[] voorbeeldfoto = rs.getBytes("Uploadfoto");
JLabel image1 = (JLabel) model.getValueAt(i, 8);
ImageIcon image1Icon = (ImageIcon) image1.getIcon();
voorbeeldfoto.setIcon(image1Icon);
} catch (ClassNotFoundException | SQLException ex) {
JOptionPane.showMessageDialog(rootPane, name);
}
}

Fetching image from database and directly read it into panel

I am fetching a image from database and directly read it into panel using Imageio.read method with Bufferimage reference variable but it gives me error javax.imageio.IIOException: Can't read input file! I don't understand why it gives me error.
My database code:
public class ValidateClass {
public static byte[] validateImageAndEmpId(Connection con, String empId) {
byte[] imagedata = null;
try {
PreparedStatement ps = con.prepareStatement("select image from fingerprint where empId=?");
ps.setString(1, empId);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
Blob blob = rs.getBlob("image");
imagedata = blob.getBytes(1, (int) blob.length());
System.out.println("Length" + imagedata);
System.out.println("testlen" + imagedata.length);
}
} catch (Exception e) {
e.printStackTrace();
}
return imagedata;
}
}
Code where I call this method:
public CEntityForm() {
jButtonStep1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jButtonStep3_actionPerformed(e);
}
});
/*jButtonStep1 for 1 to 1 match fingerprint matching which is not in use */
jtool.add(jButtonStep1);
try {
// Taking picture1
//Set picture new
m_bimage1 = ImageIO.read(new File(new java.io.File("").getAbsolutePath() + "\\L1Right.Jpeg"));
m_panel1.setBufferedImage(m_bimage1);
//Send image for skeletinization
m_finger1.setFingerPrintImage(m_bimage1);
finger1 = m_finger1.getFingerPrintTemplate();
//See what skeletinized image looks like
m_bimage1 = m_finger1.getFingerPrintImageDetail();
m_panel1.setBufferedImage(m_bimage1);
//fingerprint matching details of finger 1 in number format so commented jtextfield2
// jTextField1.setText(m_finger1.ConvertFingerPrintTemplateDoubleToString(finger1));
/*end of picture 1 details*/
// Taking picture2
//Set picture new
Connection con = Conn.getConnection();
byte[] bytearry = ValidateClass.validateImageAndEmpId(con, $emp_Id);
// System.out.println("Input="+input);
m_bimage2 = ImageIO.read(new ByteArrayInputStream(bytearry));
// m_bimage2 = ImageIO.read(new File(new java.io.File("").getAbsolutePath() + "\\L1Right_Copy.Jpeg"));
m_panel2.setBufferedImage(m_bimage2);
//Send image for skeletinization
m_finger2.setFingerPrintImage(m_bimage2);
finger2 = m_finger2.getFingerPrintTemplate();
//See what skeletinized image looks like
m_bimage2 = m_finger2.getFingerPrintImageDetail();
m_panel2.setBufferedImage(m_bimage2);
//fingerprint matching details of finger 2 in number format so commented jtextfield2
//jTextField2.setText(m_finger2.ConvertFingerPrintTemplateDoubleToString(finger2));
/*end of picture 1 details*/
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.PLAIN_MESSAGE);
}
this.getContentPane().setLayout(new GridLayout(2, 2));
this.getContentPane().add(m_panel1);
this.getContentPane().add(m_panel2);
this.getContentPane().add(jtool);
this.setTitle("Entity");
this.setSize(new Dimension(800, 700));
}
Main Method
public class Testmain {
public static void main(String[] args) {
try{
new CEntityForm().setVisible(true);
}catch(Exception e){
e.printStackTrace();
}
}
Output:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1301)
at main.CEntityForm.<init>(CEntityForm.java:81)
at main.Testmain.main(Testmain.java:18)
The exception seems to come from your other call to ImageIO.read(); the first one in the constructor. There you're passing a file that presumably doesn't exist.

retrive and display multiple BLOB images from mySQL DB

I have managed to display the first image but it does not display the next blob image in the column
PS. i have double checked everything in the DB even used the query in a Workbench THE query in the code is correct!, it returns exactly what i wanted
Thank you in advance.
My code:
public BufferedImage image()
{
System.out.println("I am in Image");
try {
System.out.println("trying to find com.mysql.jdbc.driver");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, password);
System.out.println("Success");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select image from images where state = 0 ");
while (rs.next())
{
java.sql.Blob blob = rs.getBlob(1);
System.out.println(blob);
System.out.println(blob.length());
InputStream in = blob.getBinaryStream(1,blob.length());
System.out.println(!rs.next());
System.out.println(in);
BufferedImage image = ImageIO.read(in);
System.out.println(image);
// Display the image
ImageIcon icon = new ImageIcon(image);
JLabel lbl=new JLabel();
lbl.setIcon(icon);
JFrame frame=new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(500,800);
frame.add(lbl);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
return image;
}
con.close();
System.out.println("reached here");
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
the Problem was that for some reason it was skipping one row after changing if(!rs.next) to
if (rs.next())
{
anyResults = true;
Blob blob = rs.getBlob("image");
id = rs.getInt("id");
System.out.println(id);
System.out.println(blob);
System.out.println(blob.length());
InputStream in = blob.getBinaryStream(1, blob.length());
now it works for me

Image saving in database from jLabel

I have write the code below. I can choose image using FileChooser clicking button a button(jButton5) on a Label(jLabel4). Now I want to save the imagePath in database clicking another button(jButton1). Which code should I write for jButton1.
Someone please help me.
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc=new JFileChooser();
fc.showOpenDialog(this);
File f=fc.getSelectedFile();
String path=f.getAbsolutePath();
jLabel4.setIcon(new ImageIcon(path));
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
}
If you want to store file location into database
Upload the file to some location.
Get uploaded file path
store that file path into some table.
If you want to store Images directly into Databse
Create table like below (MySql)
CREATE TABLE `IMAGES` (
`ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`IMAGE` LONGBLOB NOT NULL,
PRIMARY KEY(`ID`)
)
TYPE = InnoDB;
In your actionlistener
PreparedStatement ps = null;
InputStream is = null;
try {
con = // get your database connection
ps = con.prepareCall("insert into IMAGES values (?)");
is = new FileInputStream(new File("file path"));
ps.setBinaryStream(1, is);
int count = ps.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally{
try{
if(is != null) is.close();
if(ps != null) ps.close();
if(con != null) con.close();
} catch(Exception ex){}
}

Categories