Image not visible in JLabel with mouse click in JTable - java

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);
}
}

Related

Empty search bar, displays nothing in the jtable connected to database

When I search somethings it displays records correctly, but when I clear the search bar text it displays nothing. How can I make it so when there is nothing typed in the search bar it shows all the table records?
image of searching text in search bar
image of empty search bar
Code:
txtKerko = new JTextField();
txtKerko.setBounds(814, 60, 157, 38);
frmRegjistrimi.getContentPane().add(txtKerko);
txtKerko.setColumns(10);
txtKerko.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
try {
String id = txtpacientID.getText();
pst = con.prepareStatement("select * from pacientat where emri = ?");
pst.setString(1,txtKerko.getText());
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
if(rs.next()==true)
{
String emri = rs.getString(1);
String mbiemri = rs.getString(2);
String mosha = rs.getString(3);
String tel = rs.getString(4);
String vendbanimi = rs.getString(5);
String gjinia = rs.getString(6);
String sherbimi = rs.getString(7);
String pagesa = rs.getString(8);
String mjeku = rs.getString(9);
txtemri.setText(emri);
txtmbiemri.setText(mbiemri);
txtmosha.setText(mosha);
txttel.setText(tel);
txtvendbanimi.setText(vendbanimi);
combobox_gjinia.setSelectedItem(gjinia);
combobox_sherbimi.setSelectedItem(sherbimi);
txtpagesa.setText(pagesa);
txtmjeku.setText(mjeku);
}
else
{
txtemri.setText("");
txtmbiemri.setText("");
txtmosha.setText("");
txttel.setText("");
txtvendbanimi.setText("");
combobox_gjinia.setSelectedItem("Zgjidhni Gjininë:");
combobox_sherbimi.setSelectedItem("Zgjidhni Shërbimin:");
txtpagesa.setText("");
txtmjeku.setText("Dr.");
}
}
catch (SQLException ex) {
}
}}
);
The txtkerko is the search bar when is in JTextField
image of searched records

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

JDBC JTable image

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.

How to fill a JTable with data from a DB?

I'm trying to display a list of data when I click on a button.
Now, I have a an homepage (a jframe that is the homepage of the program) with a button that will open the list frame and that button, when it will be clicked, will get the data from my DB and update the table.
This is the code that I've wrote on the button that is in the homepage and not in the list frame
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new List().setVisible(true);
}
});
this.dispose();
String DB_URL = "jdbc:mysql://localhost:3306/registropassword?autoReconnect=true&useSSL=false";
String DB_Username = "root";
String DB_Password = "root";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, DB_Username, DB_Password);
PreparedStatement prepstmt = null;
ResultSet rs = null;
String query = "SELECT * FROM registro";
prepstmt = conn.prepareStatement(query);
rs = prepstmt.executeQuery();
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
} catch (ClassNotFoundException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
}
NOTE:
On this line of code the jTable2, that is the name of the table that should be updated, I got a 'cannot find symbol' error on this line.
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
Can someone help me to figure out where I'm wrong?

Load data from MySQL into JComboBox

I have two MySQL tables as image below
movie
movie_title
JComboBox combo = new JComboBox();
combo.setBounds(125, 15, 190, 20);
try {
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Select title FROM movie_title";
PreparedStatement ps=connect.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String name = rs.getString("title");
combo.addItem(name);
}
} catch (Exception e) {
System.out.println("null");
}
combo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
JComboBox comboBox=(JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
displayDay(selected);
}
private void displayDay(Object selected) {
// TODO Auto-generated method stub
try {
combo1.removeAllItems();
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Select movie_day FROM movie WHERE movie_title = ?";
PreparedStatement ps=connect.prepareStatement(sql);
ps.setObject(1, selected);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String day = rs.getString("movie_day");
combo1.addItem(day);
}
} catch (Exception e) {
System.out.println("null");
}
}
});
I have implemented ActionListener in comboBox. When user select movie Marvel's Captain America, it will get the movie_day item from movie and load into combo1. Is there a way I can make the combo1 display the movie_day which is Sunday, 28 Apr 2016 one time only instead of two ?
Edit
private void displayDay(Object selected) {
// TODO Auto-generated method stub
try {
combo1.removeAllItems();
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Select movie_day FROM movie WHERE movie_title = ?";
PreparedStatement ps=connect.prepareStatement(sql);
ps.setObject(1, selected);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String day = rs.getString("movie_day");
DefaultComboBoxModel model = (DefaultComboBoxModel)combo1.getModel();
if (model.getIndexOf(day) == -1)
{
combo1.addItem(day);
}
}
} catch (Exception e) {
System.out.println("null");
}
Is there a way I can make the combo1 display the movie_day which is Sunday, 28 Apr 2016 one time only instead of two ?
Before adding the date to the combo box you need to check if the date already exists.
DefaultComboBoxModel model = (DefaultComboBoxModel)comboBox.getModel();
if (model.getIndexOf(theDate) == -1)
{
comboBox.addItem( theDate );
}
You could also change the SQL statement to only get "unique" dates, but I don't know SQL well enough to give you the actual syntax. Maybe this SQL Tutorial will help, otherwise you need to find a better tutorial.

Categories