I'm using the next code to show image in label , to set nothing to label when picture column is null :
ResultSet rset2 = stmnt.executeQuery("select Picture from Pictures where Client_ID_pass =1" );
while(rset2.next()){
byte[] Passimg = rset2.getBytes("Picture");
//Resize The ImageIcon
ImageIcon Passimage = new ImageIcon(Passimg);
Image Passim = Passimage.getImage();
Image PassmyImg = Passim.getScaledInstance(PassLBL.getWidth(), PassLBL.getHeight(),Image.SCALE_SMOOTH);
ImageIcon newPassImage = new ImageIcon(PassmyImg);
PassLBL.setIcon(newPassImage);
if(Passimg.length < 0){
PassLBL.settext("No Picture");
PassLBL.setIcon(null);
}
}
I've tried the next :
if(Passimg.equals(null)
{PassLBL.settext("No Picture");}
and tried
if(Passimg == null)
{PassLBL.settext("No Picture"); }
but didn't work !
when you retrive the data from the resultSet
byte[] Passimg = rset2.getBytes("Picture");
put if statement there
if(passimg == null) {
label.setText("nothing")
lable.setIcon(null);//to remove the old picture
}else {
//show the image like you did before
lable.setText("");
icon=create your icon here
lable.setIcon(icon);
}
i didn't undertand what you need exactly hope this help you
I have a table called 'tab1'
cl_id int //auto imcrement
cl_image image
i want to read a image from excel with image and store it in the above table
FileInputStream fileInputStream = new FileInputStream(
"Delux.xls");
System.out.println(fileInputStream);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet("Delux");
Iterator rows = worksheet.rowIterator();
HSSFRow row = (HSSFRow) rows.next();
List lst = workbook.getAllPictures();
Iterator it = lst.iterator();
while (rows.hasNext()) {
row = (HSSFRow) rows.next();
//reading the image from excel
HSSFCell cellP1 = row.getCell((short) 1);
PictureData pict = (PictureData)it.next();
String ext = pict.suggestFileExtension();
byte[] data = pict.getData();
InputStream is = new ByteArrayInputStream(data);
try {
PreparedStatement stmt = getdbconn()
.prepareStatement(
"insert into tab1 (cl_image) values(?)");
stmt.setBinaryStream(1, is);
stmt.executeUpdate();
is.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
but when i store the image dynamically i getting the error like
"String or binary data would be truncated".
Can anyone suggest me a method to achieve this???
Data Types like IMAGE and TEXT not going to be supported and they are deprecated.
So Change it to VARBINARY(max).Most import thing is taht IMAGE data type requires storing the size in a special way rather than expanding VARBINARY to cater for anything all the way to 2GB. The error you get was raised becasue image not fit in cl_image field.
I have a small requirement please help me
Firstly, I have a label, i set a icon to that label as
lbl_photo.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/images/photo.png")));
and i have a button browse to select the image.
private void btn_browseActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"jpeg, gif and png files", "jpg", "gif", "png");
int i = chooser.showOpenDialog(this);
if (i == JFileChooser.APPROVE_OPTION) {
image = chooser.getSelectedFile();
try {
BufferedImage originalImage = ImageIO.read(image);
int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
: originalImage.getType();
BufferedImage resizeImageJpg = resizeImage(originalImage, type);
photo = new ImageIcon(toImage(resizeImageJpg));
raster = resizeImageJpg.getRaster();
data = (DataBufferByte) raster.getDataBuffer();
} catch (Exception e) {
System.out.println(e.getMessage());
}
lbl_photo.setIcon(photo);
}
}
now, I am storing the selected image from browse button into database
Date date1 = new Date();
Timestamp timestamp1 = new Timestamp(date1.getTime());
String sql4 = "insert into std_photos values(?,?,?)";
pstmt5 = con.prepareStatement(sql4);
pstmt5.setInt(1, Integer.parseInt(txt_eno.getText()));
pstmt5.setString(2, "");
pstmt5.setTimestamp(3, timestamp1);
byte[] extractBytes = data.getData();
pstmt5.setBytes(2, extractBytes);
System.out.println(sql4);
image is successfully storing.but,if the user doesn't select the image through browse button the default jlabel icon should be store in the database.
please help me as early as possible
You are already checking the return value of chooser.showOpenDialog(this) for JFileChooser.APPROVE_OPTION.
In case you receive some other option or if the try-catch block reading the new image fails you could just get the old icon and write it into the database.
After I add a new row to a JTable. The information wrote goes to the txt file, but my JTable doesn't shows the last raw. But if I close the program, and run it again, the information it's in the table. So, is there a way to refresh the data in the JTable without closing the application and running it again?
String[] columns = {"nume", "compozitie", "indicatii", "contraindicatii", "administrare", "pret", "compensabil", "stoc"};
Object[][] data = null;
try {
File file = new File("medicamente.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
data = new Object[100][];
String line;
int numLines = 0;
while ((line = bufferedReader.readLine()) != null) {
data[numLines] = line.split(",");
numLines++;
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
TableModel model = new DefaultTableModel(data, columns) {
#Override
public Class getColumnClass(int column) {
Class returnValue;
if ((column >= 0) && (column < getColumnCount())) {
returnValue = getValueAt(0, column).getClass();
} else {
returnValue = Object.class;
}
return returnValue;
}
};
JTable table = new JTable(model) {
public boolean isCellEditable(int row, int column) {
return false;
}
};
final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
table.setRowSorter(sorter);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(1000, 500));
mainPanel.add(scrollPane);
scrollPane.setBounds(0, 240, 995, 510);
final JTextField filterText = new JTextField(null);
mainPanel.add(filterText);
filterText.setBounds(0, 750, 850, 25);
JButton button = new JButton("Filter");
mainPanel.add(button);
button.setBounds(850, 750, 150, 25);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = filterText.getText();
if (text.length() == 0) {
sorter.setRowFilter(null);
// model.fireTableDataChanged();
} else {
sorter.setRowFilter(RowFilter.regexFilter(text));
}
}
});
It looks like what you think is that when the file updates, so should the JTable. It doesn't work like that. What you need to do is add a row to the TableModel. A disadvantage in your case is this
TableModel model = new DefaultTableModel( data, columns)
You're using the TableModel interface, which has very limited methods you can use. Instead do this
DefaultTableModel model = new DefaultTableModel( data, columns)
Then you can use one of these methods from DefaultTableModel
public void addRow(Object[] rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
public void addRow(Vector rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
So when you want to add a row, you can gather your data into an array, addRow(..) then the table will get automatically update for you.
Object[] row = { data1, data2, data2, data4, data5 };
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(row);
Also it looks to me like your JTable is locally scoped. You may want to give it a global, class member scope, so you can access it from where ever you need to.
you must add your data to the model of jtable and then add the model to jtable and it will be refreshed , but before that you have to define a model .
Use this code.
private void resetListData() throws ClassNotFoundException, SQLException
{
Connection cne = null;
try {
// create connection in this line as per your database like I used sqlite. so my connection string is as follow
Class.forName("org.sqlite.JDBC");
cne = DriverManager.getConnection("jdbc:sqlite:table.sqlite");
cne.setAutoCommit(false);
PreparedStatement psd = (PreparedStatement) cne.prepareStatement("Select * from table");
psd.execute();
ResultSet r = psd.getResultSet();
ResultSetMetaData rsmd = r.getMetaData();
int count = rsmd.getColumnCount();
String[] meta = new String[count];
for (int i = 0; i < count; i++)
{
String name = rsmd.getColumnName(i + 1);
meta[i] = name;
//System.out.println(name);
}
model = new DefaultTableModel(new Object[][]{}, new String[]{"name", "address"});
jTable1.setModel(model);
while (r.next())
{
Object[] row = new Object[count];
for (int i = 1; i <= count; ++i)
{
row[i - 1] = r.getString(i); // Or even rs.getObject()
}
model.addRow(row);
}
cne.close();
} catch (ClassNotFoundException | SQLException e) {
}
}
create connection and query as per your need.. my code add one row at the end of Jtable. My code directly working with your database..
Thanks..
by the way why you're using TableRowSorter in your code , why you don't use just the jtable and defaultmodel directly
I recently had the same problem and the solution was to call
model.fireTableDataChanged();
right after adding the new row to the model.
My issue was the following: I had a table on which I allowed sorting. Without clicking the column headers so that the rows would sort accordingly, I was able to add data to the model and see the changes in the table by calling table.revalidate(); However, if, at any time, I clicked the column headers, any row added afterwards wouldn't be shown, although the model data was updating properly. By only calling model.fireTableDataChanged(); after adding the data to the model, it works as a charm.
I am trying to retrieve blob data type from database table and display the image in a imageView. Here is my select SQL statement:
public boolean retrieve(){
boolean success = false;
ResultSet rs = null;
DBController db = new DBController();
db.getConnection();
String dbQuery = "SELECT * FROM sm_product WHERE productName ='" + name +"'";
rs = db.readRequest(dbQuery);
try {
if(rs.next()){
desc = rs.getString("productDescription");
price = rs.getInt("productPrice");
quantity = rs.getInt("productQuantity");
dateStr = rs.getString("dateOfCreation");
category = rs.getString("productCategory");
Blob blob = rs.getBlob("productImage");
byte[] data = blob.getBytes(0, (int) blob.length());
image = ImageIO.read(new ByteArrayInputStream(data)); //Error here
success = true;
}
}
catch(Exception e){
e.printStackTrace();
}
db.terminate();
return success;
}
After retrieved, I want to display it in a imageview. Here is the code:
panel.getMyImageView().setImage(product.getImage());
However, I got incompatible type error message. I know image = ImageIO.read(new ByteArrayInputStream(data)); this line supposed to store as BufferedImage and then from there I slowly convert to image datatype and display in image view. But after 2 hours of researching, I got no luck. Can somebody please help me with it?
Thanks in advance.
Toolkit.getDefaultToolkit().createImage(data)
Call this for the byte array read from the blob