I can't populate a JComboBox with an ArrayList - java

I have two classes, one has an ArrayList called "clanovi" which is populated by data from SQL database and I want to display that data in the "clanComboBox" in another class. I have been trying for two days but I can't figure it out.
Class with the list:
String cnnString;
String user;
String password;
public ArrayList<String> clanovi = new ArrayList<String>();
public ArrayList<String> getList(){
return clanovi;
}
public void Connect(String cnnString, String user, String password){
this.cnnString = cnnString;
this.user = user;
this.password = password;
ResultSet res = null;
try {
Connection connection = DriverManager.getConnection(cnnString, user, password);
System.out.println("Connection successful");
Statement stm = connection.createStatement();
String sql = "select Ime, Prezime from Clanovi";
res = stm.executeQuery(sql);
while(res.next()) {
clanovi.add(res.getString("Ime") + " " + res.getString("Prezime"));
}
System.out.println(clanovi);
} catch (SQLException e) {
System.out.println("An unexpected error occurred.");
e.printStackTrace();
}
}
The GUI class with the combobox:
public class PosuditiFilmFrame implements ActionListener{
SQLConnection con = new SQLConnection();
JFrame posuditiFilmFrame = new JFrame();
JButton posuditiFilmButton = new JButton();
JComboBox clanoviComboBox = new JComboBox();
JComboBox filmoviComboBox = new JComboBox();
JLabel clanLabel = new JLabel("Clan:");
JLabel filmLabel = new JLabel("Film:");
ArrayList<String> cBox = con.getList();
PosuditiFilmFrame(){
posuditiFilmButton = new JButton();
posuditiFilmButton.setBounds(200, 270, 200, 50);
posuditiFilmButton.addActionListener(this);;
posuditiFilmButton.setText("Posuditi Film");
posuditiFilmButton.setFocusable(false);
clanLabel.setBounds(50, 50, 70, 50);
clanLabel.setFont(new Font("Arial", Font.PLAIN, 25));
filmLabel.setBounds(50, 125, 70, 50);
filmLabel.setFont(new Font("Arial", Font.PLAIN, 25));
clanoviComboBox.setBounds(150, 50, 300, 50);
filmoviComboBox.setBounds(150, 125, 300, 50);
posuditiFilmFrame.setTitle("Posuditi Film");
posuditiFilmFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
posuditiFilmFrame.setLayout(null);
posuditiFilmFrame.setSize(600, 400);
posuditiFilmFrame.setVisible(true);
posuditiFilmFrame.add(posuditiFilmButton);
posuditiFilmFrame.add(clanoviComboBox);
posuditiFilmFrame.add(filmoviComboBox);
posuditiFilmFrame.add(clanLabel);
posuditiFilmFrame.add(filmLabel);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==posuditiFilmButton) {
JOptionPane.showMessageDialog(null, "Film je posuden");
}
}
Of course, I also want the data to be displayed in that combobox

Related

Adding a hyperlink to a single value of sql in jTable

I am implementing a search interface in eclipse with the help of mysql. My search interface yields the results I want, but I want to be able to have the "video_url" column clickable and bring up a hyperlink. Is there a way to do this for a single column? Right now the Jtable is "editable", so the user can click on it, but no changes are made to it. The link can be copied and then pasted later, but I'm really trying to have the link be opened from the interface.
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
VIdeo_search_test window = new VIdeo_search_test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public VIdeo_search_test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 17));
frame.setBounds(400, 400, 1050, 1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblVideoSearch = new JLabel("Video Search");
lblVideoSearch.setFont(new Font("Tahoma", Font.PLAIN, 19));
lblVideoSearch.setBounds(241, 11, 230, 27);
frame.getContentPane().add(lblVideoSearch);
JButton btnSearchCity = new JButton("Search City");
btnSearchCity.setBounds(216, 80, 165, 25);
btnSearchCity.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = new DefaultTableModel(new String[]{"video_url", "video name", "video description", "video_city", "video_subject", "video_tags", "reviewed_by", "star"}, 0);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/userdatabase", "root", "pass1234");
Statement stmt= con.createStatement();
String sql = "Select * from video where video_city = '" +txtCity.getText()+"'";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
String a = rs.getString("video_url");
String d = rs.getString("video_name");
String e = rs.getString("video_description");
String f = rs.getString("video_city");
String g = rs.getString("video_subject");
String h = rs.getString("video_tags");
String k = rs.getString("reviewed_by");
String i = rs.getString("star");
model.addRow(new Object[]{a, d, e, f, g, h, k, i});
table.setModel(model);
}
{
con.close();}
} catch(Exception e) {System.out.print (e);}
}
});
frame.getContentPane().add(btnSearchCity);
JButton btnSearchTag = new JButton("Search Tag");
btnSearchTag.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = new DefaultTableModel(new String[]{"video_url", "video name", "video description", "video_city", "video_subject", "video_tags", "reviewed_by", "star"}, 0);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/userdatabase", "root", "pass1234");
Statement stmt= con.createStatement();
String sql = "Select * from video where video_tags LIKE '"+txtTag.getText()+"%'";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
String a = rs.getString("video_url");
String d = rs.getString("video_name");
String e = rs.getString("video_description");
String f = rs.getString("video_city");
String g = rs.getString("video_subject");
String h = rs.getString("video_tags");
String k = rs.getString("reviewed_by");
String i = rs.getString("star");
model.addRow(new Object[]{a, d, e, f, g, h, k, i});
table_1.setModel(model);
}
{
con.close();}
} catch(Exception e) {System.out.print (e);}
}
});
btnSearchTag.setBounds(216, 303, 165, 25);
frame.getContentPane().add(btnSearchTag);
txtCity = new JTextField();
txtCity.setBounds(216, 49, 165, 20);
frame.getContentPane().add(txtCity);
txtCity.setColumns(10);
table = new JTable();
table.setBounds(10, 116, 867, 135);
frame.getContentPane().add(table);
txtTag = new JTextField();
txtTag.setColumns(10);
txtTag.setBounds(216, 272, 165, 20);
frame.getContentPane().add(txtTag);
table_1 = new JTable();
table_1.setBounds(10, 341, 601, 135);
frame.getContentPane().add(table_1);
JButton btnViewVideo = new JButton("View Video");
btnViewVideo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
registered_video_interface info = new registered_video_interface();
registered_video_interface.main(null); }
});
btnViewVideo.setBounds(251, 509, 89, 23);
frame.getContentPane().add(btnViewVideo);
}
}

Data submission not working while using Swing application otherwise it works normally

When i write PreparedStatement in main function, it works perfectly and submits the data but when i write in in actionPerformed function it doesn't work, why??
I don't think I'm doing anything wrong.
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
public class EnterData {
static void insertData(int rn, String fn, String ln) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo","root","12345")) {
String query = "insert into student (rollno, fname, lname)" + " values (?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt (1, rn);
preparedStmt.setString (2, fn);
preparedStmt.setString (3, ln);
preparedStmt.execute();
}
}
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Submit Information");
mainFrame.setSize(400, 300);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLocationRelativeTo(null);
mainFrame.setLayout(null);
JLabel heading = new JLabel("Enter Data");
heading.setBounds(150, 10, 100, 20);
mainFrame.add(heading);
JLabel rollnoLabel = new JLabel("Roll Number");
rollnoLabel.setBounds(70, 60, 100, 20);
mainFrame.add(rollnoLabel);
JTextField rollno = new JTextField();
rollno.setBounds(220, 60, 100, 20);
mainFrame.add(rollno);
// Taking First Name
JLabel name1 = new JLabel("First Name");
name1.setBounds(70, 110, 100, 20);
mainFrame.add(name1);
JTextField fname = new JTextField();
fname.setBounds(220, 110, 100, 20);
mainFrame.add(fname);
// Taking Last Name
JLabel name2 = new JLabel("Last Name");
name2.setBounds(70, 160, 100, 20);
mainFrame.add(name2);
JTextField lname = new JTextField();
lname.setBounds(220, 160, 100, 20);
mainFrame.add(lname);
// Submit and Reset Button
JButton submit = new JButton("Submit");
submit.setBounds(70, 220, 100, 20);
mainFrame.add(submit);
JButton reset = new JButton("Reset");
reset.setBounds(220, 220, 100, 20);
mainFrame.add(reset);
// Frame Visibility
mainFrame.setVisible(true);
submit.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
int rn = Integer.parseInt(rollno.getText());
String fn = fname.getText();
String ln = lname.getText();
insertData(rn, fn, ln);
JOptionPane.showMessageDialog(null, "Submitted Successfully...!!!", "Submission Prompt", JOptionPane.PLAIN_MESSAGE);
} catch (Exception ex) {
System.err.println("Got an exception!");
System.err.println(ex.getMessage());
}
}
});
}
}
I've tried this and it works perfectly but when i put those statements in actionPerformed function they don't work.
import java.sql.*;
public class DatabaseTest {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo","root","12345");
String query = "insert into student (rollno, fname, lname)" + " values (?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt (1, 6505);
preparedStmt.setString (2, "Prince");
preparedStmt.setString (3, "Saini");
preparedStmt.execute();
conn.close();
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}

how to set values from sql database to java textbox?

When I try to access data from SQL Server, the data column is of type varchar. But I try to set it into textbox, I got these type of exception
Conversion failed when converting the varchar value '09ran01' to data type int
package src.ui;
import src.ui.ImageHandler;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.event.*;
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.DateFormat;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class AddAccount extends JPanel implements ActionListener, DocumentListener, KeyListener {
String imagefolder = ImageHandler.returnimagepath();
Image bgImage = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/src/ui/images/bgc.jpg"));
private static final long serialVersionUID = 1L;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
String iden[] = {"Student","Others"};
String type[] = {"Account User", "Walkthrough User"};
JLabel userid = new JLabel("USER ID");
JLabel name = new JLabel("FULL NAME");
JLabel pswrd = new JLabel("PASSWORD");
JLabel ident = new JLabel("IDENTIFICATION");
JLabel idno = new JLabel("ID NUMBER");
JLabel Add = new JLabel("ADDRESS");
JLabel acctype = new JLabel("ACCOUNT TYPE");
JTextField userFld = new JTextField(10);
JTextField nameFld = new JTextField(10);
JPasswordField pswrdFld = new JPasswordField(10);
JComboBox identC = new JComboBox(iden);
JComboBox actype = new JComboBox(type);
JTextField idFld = new JTextField(10);
JTextArea addArea = new JTextArea(10, 10);
JButton okButton = new JButton("OK");
JButton exitButton = new JButton("RESET");
JButton b1 = new JButton("SEARCH");
JScrollPane scroll = new JScrollPane(addArea);
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1/cybman", "root", "");
} catch (Exception e) {
//System.out.println(e);
}
return conn;
}
public static Connection getConnection1() {
Connection con = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://localhost\\BCA1:1433;databaseName=Old_Bhandarkars;user=sa;password=1234");
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"SERVER ERROR");
//System.out.println(e);
}
return con;
}
public void changedUpdate(DocumentEvent ev) {
}
public void removeUpdate(DocumentEvent ev) {
}
public void insertUpdate(DocumentEvent ev) {
}
public void paintComponent(Graphics g) {
g.drawImage(bgImage, 0, 0, this);
}
public void init() {
setLayout(null);
okButton.addActionListener(this);
b1.addActionListener(this);
exitButton.addActionListener(this);
pswrdFld.addActionListener(this);
pswrdFld.setEchoChar('*');
addArea.getDocument().addDocumentListener(this);
identC.addActionListener(this);
actype.addActionListener(this);
userid.setBounds(270, 20, 120, 20);
userFld.setBounds(470, 20, 140, 20);
b1.setBounds(670, 20, 100, 20);
name.setBounds(270, 70, 120, 20);
nameFld.setBounds(470, 70, 140, 20);
pswrd.setBounds(270, 120, 120, 20);
pswrdFld.setBounds(470, 120, 140, 20);
ident.setBounds(270, 170, 120, 20);
identC.setBounds(470, 170, 140, 20);
idno.setBounds(270, 220, 120, 20);
idFld.setBounds(470, 220, 140, 20);
acctype.setBounds(270, 270, 120, 20);
actype.setBounds(470, 270, 140, 20);
Add.setBounds(270, 320, 320, 20);
scroll.setBounds(470, 320, 140, 60);
okButton.setBounds(270, 410, 100, 20);
okButton.addKeyListener(this);
exitButton.setBounds(510, 410, 100, 20);
}
public AddAccount() {
init();
add(userid);
add(userFld);
add(name);
add(nameFld);
add(pswrd);
add(pswrdFld);
add(ident);
add(identC);
add(idno);
add(idFld);
add(acctype);
add(actype);
add(Add);
add(b1);
add(scroll);
add(okButton);
add(exitButton);
}
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
public class Function
{
Connection con=getConnection1();
ResultSet rs;
public ResultSet find(String s)
{
int a=Integer.parseInt(s);
try{
Statement sta = con.createStatement();
String s1 = "select * from Members where Fld_Member_Id="+a+"";
rs = sta.executeQuery(s1);
}
catch(Exception ex){
JOptionPane.showMessageDialog(null,"No connection");
//JOptionPane.showMessageDialog(null,ex.getMessage());
}
//JOptionPane.showMessageDialog(null,rs);
return rs;
}
}
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
char[] pass;
String uid;
String nam;
String add;
String id;
String idnum;
String actyp;
int amt = 0;
String datE;
if (str.equals("SEARCH")) {
Function f=new Function();
ResultSet rs=null;
String n1="Fld_First_Name";
String i1="Fld_Member_Id";
String address="Fld_PAddr";
uid = userFld.getText();
if(uid.equals(""))
{
JFrame msg=new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the user id", "Error Message", JOptionPane.ERROR_MESSAGE);
}
// simple.main();
else
{
//idFld.setText(userFld.getText());
rs=f.find(userFld.getText());
// System.out.println("Fld_First_Name");
try{
if(rs.next()){
// int i = Integer.parseInt(rs.getString("Fld_First_Name"));
// int j = Integer.parseInt(rs.getString("Fld_Member_Id"));
// int k = Integer.parseInt(rs.getString("Fld_PAddr"));
nameFld.setText(rs.getString("Fld_First_Name"));
idFld.setText(rs.getString("Fld_Member_Id"));
addArea.setText(rs.getString("Fld_PAddr"));
}
else
{
JOptionPane.showMessageDialog(null,"No data");
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
}
if (str.equals("OK")) {
try {
uid = userFld.getText();
nam = nameFld.getText();
pass = pswrdFld.getPassword();
add = addArea.getText();
idnum = idFld.getText();
id = (String) identC.getSelectedItem();
actyp = (String) actype.getSelectedItem();
datE = getDateTime();
String pwrd = new String(pass);
Connection conn = getConnection();
/*ERROR CHECKING*/
boolean success = true;
if (uid.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the user id", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if (nam.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the name", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if (pwrd.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the password", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if ((!id.equals("Student")) && (idnum.equals(""))) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the identification number", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if (add.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the address", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
}
/*end of ERROR CHECKING*/
if (success == true) {
///////////ENSURE/////////
JFrame msg = new JFrame();
int choice;
choice = JOptionPane.showConfirmDialog(msg, "Are you sure?", "Select your choice", JOptionPane.OK_CANCEL_OPTION);
/////////////////////////
if (choice == JOptionPane.OK_OPTION) {
str = "insert into account(userid,name,password,address,identification,identificationnum,amount,dates,acctype" + ") values (?,?,?,?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(str);
ps.setString(1, uid);
ps.setString(2, nam);
ps.setString(3, pwrd);
ps.setString(4, add);
ps.setString(5, id);
ps.setString(6, idnum);
ps.setInt(7, amt);
ps.setString(8, datE);
ps.setString(9, actyp);
int count;
count = ps.executeUpdate();
count++;
count--;
//////////////////////////////
ReportPanel.userC.addItem(uid);
ViewAccount.userC.addItem(uid);
if (actyp.equals("Account User")) {
RechargePanel.userC.addItem(uid);
}
//////////////////////////////
JFrame msg1 = new JFrame();
JOptionPane.showMessageDialog(msg1, "An account has been successfully created", "Information", JOptionPane.INFORMATION_MESSAGE);
} else if (choice == JOptionPane.CANCEL_OPTION) {
JOptionPane.showMessageDialog(msg, "Account Creation Aborted", "Information", JOptionPane.INFORMATION_MESSAGE);
}
}
//conn.close();
} catch (SQLException e1) {
String error;
JFrame msg = new JFrame();
//error=e1.toString();
error = "Your entry for user id already exists";
JOptionPane.showMessageDialog(msg, error, "Error Message", JOptionPane.ERROR_MESSAGE);
} catch (Exception e1) {
// TODO Auto-generated catch block
String error;
JFrame msg = new JFrame();
error = e1.toString();
JOptionPane.showMessageDialog(msg, error, "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
///////////////////////////////////////////////////////////////////////////
if (str.equals("RESET")) {
try {
userFld.setText("");
nameFld.setText("");
pswrdFld.setText("");
addArea.setText("");
idFld.setText("");
} catch (Exception e2) {
String error;
JFrame msg = new JFrame();
error = e2.toString();
JOptionPane.showMessageDialog(msg, error, "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
}
///////////////////////////////////////////////////////////
public void keyPressed(KeyEvent key) {
//
}
/////////////////////////////////////////////////////
public void keyReleased(KeyEvent key) {
if (key.getSource() == pswrdFld) {
if (key.getKeyCode() == KeyEvent.VK_ENTER) {
}
}
}
/////////////////////////////////////////////////
public void keyTyped(KeyEvent key) {
//
}
//////////////////////////////////////////////
}
How to set all values to textbox?
field name data type
---------------------------------------------------------------------
Fld_First_Name varchar
Fld_Member_Id varchar
Fld_PAddr nvarchar
SELECT * FROM Members where Fld_Member_Id='14932';
_____________________________________________________________________________
Fld_Member_Id Fld_First_Name Fld_PAddr
______________________________________________________________________________
14932 abc abc
In WHERE clause of a SQL query a varchar variables should be within a single quotes. Try String s1 = "select * from Members where Fld_Member_Id='"+a+"'";
add Single quotes into the statement.And i think it should work setText method that you mentioned if you pass a varchar value correctly.
If you are not sure what is the type of memberID, then use
idFld.setText(String.valueOf("Your value"));

I cannot insert value in the table using textfield

I need to create a program in which values can be inserted using textfield in Java.
database getting connected ...
bt Cannot insert values using JTextfield ....need help..
shows error ..
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
package youtubetest;
import java.sql.*;
import java.awt.event.*;
import javax.swing.*;
public class YouTubeTest extends JFrame{
private static final String USERNAME = "root";
private static final String PASSWORD = "****";
private static final String CONN_STRING = "jdbc:mysql://localhost:3306/youtube";
Connection conn;
PreparedStatement stmt;
JButton b1,b2;
JTextField t1,t2;
JLabel l1,l2;
String Fname;
String Lname;
public YouTubeTest()
{
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLayout(null);
add(t1 = new JTextField(30));
t1.setBounds(10,10,200,50);
add(t2 = new JTextField(30));
t2.setBounds(10, 100, 200, 50);
add(l1 = new JLabel("First Name : "));
l1.setBounds(220, 10, 200, 50);
add(l2 = new JLabel("Last Name : "));
l2.setBounds(220, 100, 200, 50);
add(b1 = new JButton("Submit"));
b1.setBounds(10, 400, 60, 60);
add(b2 = new JButton("Clear"));
b2.setBounds(100, 400, 60, 60);
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(CONN_STRING,USERNAME,PASSWORD);
System.out.println("Database Connected Succesfully ..... ");
stmt = conn.prepareStatement("Insert into user(Fname,Lname) values('"+Fname+"','"+Lname+"')");
}catch(Exception e){
e.printStackTrace();
}
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae){
try{
Fname = t1.getText();
Lname = t2.getText();
stmt.setString(1, Fname);
stmt.setString(2, Lname);
stmt.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
t1.setText("");
t2.setText("");
}
});
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
try{
stmt.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
});
setVisible(true);
}
public static void main(String[] args)throws Exception {
new YouTubeTest();
}
};

I can't show photo blob more than once

I have a database with photos for each person. I have a class that shows the photos of the people. When the class is running first, it stores the foto locally, and then another method takes it and displays it. The problem is that the class works correctly ONLY the first time! Every other name selection displays the first picture. Please help me to identify where does this happen!
Here is my Class:
public class Profile extends JFrame {
int x;
JLabel label;
Image img;
ImageIcon pic;
JPanel panel;
private JTextPane namepanel = new JTextPane();
private JLabel namelabel = new JLabel();
private JLabel lastnamelabel = new JLabel();
private JTextPane lastnamepanel = new JTextPane();
ResultSet resultSet;
private JButton add = new JButton();
private JButton remove = new JButton();
public Profile() {
try {
//getData(x);
//showImage();
//jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
public void getData(int p_id) throws Exception {
Login login = new Login();
String url = "jdbc:oracle:thin:#localhost:1521:ORCL";
String username = login.getUsername();
String password = login.getPassword();
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username, password);
System.out.println("At the profile class id = " + p_id);
String sql = "SELECT foto, name, surname FROM criminals WHERE id = " + p_id;
System.out.println(sql);
PreparedStatement stmt = conn.prepareStatement(sql);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
namepanel.setText(resultSet.getString(2));
lastnamepanel.setText(resultSet.getString(3));
File image = new File("java.jpg");
FileOutputStream fos = new FileOutputStream(image);
byte[] buffer = new byte[256];
// Get the binary stream of our BLOB data
InputStream is = resultSet.getBinaryStream(1);
int bytes = 0;
while ((bytes = is.read(buffer)) > 0) {
fos.write(buffer, 0, bytes);
}
showImage();
fos.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null && !conn.isClosed()) {
conn.close();
}
}
}
public void showImage() throws Exception {
this.getContentPane().removeAll();
img = null;
img = new ImageIcon("java.jpg").getImage();
pic = null;
pic = new ImageIcon(img);
label = new JLabel("", pic, JLabel.CENTER);
panel = new JPanel(new BorderLayout());
panel.setBounds(new Rectangle(0, 0, 340, 310));
namepanel.setBounds(new Rectangle(340, 30, 295, 35));
namelabel.setText("Name");
namelabel.setBounds(new Rectangle(340, 0, 295, 30));
lastnamelabel.setText("Surname");
lastnamelabel.setBounds(new Rectangle(340, 65, 295, 30));
lastnamepanel.setBounds(new Rectangle(340, 105, 295, 35));
add.setText("add");
add.setBounds(new Rectangle(440, 175, 255, 40));
remove.setText("remove");
remove.setBounds(new Rectangle(440, 240, 255, 35));
panel.add(label, null);
panel.add(label, BorderLayout.CENTER);
this.getContentPane().setLayout(null);
this.setSize(new Dimension(1148, 336));
this.getContentPane().add(remove, null);
this.getContentPane().add(add, null);
this.getContentPane().add(lastnamepanel, null);
this.getContentPane().add(lastnamelabel, null);
this.getContentPane().add(namelabel, null);
this.getContentPane().add(namepanel, null);
this.getContentPane().add(panel, null);
}
The way you are using is the not way of using preparedstatement. Use this way
String sql = "SELECT foto, name, surname FROM criminals WHERE id = ?" ;
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1,p_id);
I found the solution! Here it is in case anyone else searches for it!
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username, password);
System.out.println("At the profile class id = " + p_id);
String sql = "SELECT foto, name, surname FROM criminals WHERE id = " + p_id;
System.out.println(sql);
PreparedStatement stmt = conn.prepareStatement(sql);
resultSet = stmt.executeQuery();
byte[] bytes = null;
while (resultSet.next()) {
namepanel.setText(resultSet.getString(2));
lastnamepanel.setText(resultSet.getString(3));
bytes = resultSet.getBytes(1);
}
resultSet.close();
stmt.close();
conn.close();
if (bytes != null) {
JFrame f = new JFrame();
image = f.getToolkit().createImage(bytes);
}
} catch (Exception e) {
}
jbInit();
}
public void jbInit() throws Exception {
pic = new ImageIcon(image);
label = new JLabel("", pic, JLabel.CENTER);
}

Categories