I can't show photo blob more than once - java

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

Related

I can't populate a JComboBox with an ArrayList

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

How should I delete, edit and add MySQL information with java and input?

This is where I tried to change the information from the user via text fields.
int id = Integer.parseInt(inputID.getText());
String name = inputName.getText();
int age = Integer.parseInt(inputAge.getText());
String adress = inputAdress.getText();
int income = Integer.parseInt(inputIncome.getText());
String sqlStmt = "update person set name = ?, godine = ?, adress = ?, income = ? where id = ?";
PreparedStatement prepStmt;
prepStmt = conn.prepareStatement(sqlStmt);
prepStmt.setString(1, name);
prepStmt.setInt(2, age);
prepStmt.setString(3, adress);
prepStmt.setInt(4, income);
prepStmt.setInt(5, id);
ResultSet rs = prepStmt.executeQuery();
This is where I tried to delete the user by the input in id text field.
int id = Integer.parseInt(inputID.getText());
String sqlStmt = "delete from person where id = ?";
PreparedStatement prepStmt;
prepStmt = conn.prepareStatement(sqlStmt);
prepStmt.setInt(1, id);
ResultSet rs = prepStmt.executeQuery();
This is where I tried to add a new user in the mysql database
String name = inputName.getText();
int age = Integer.parseInt(inputAge.getText());
String adress = inputAdress.getText();
int income = Integer.parseInt(inputIncome.getText());
korisnik = new Korisnik(name,age,adress,income);
PreparedStatement prepStmt;
prepStmt = conn.prepareStatement("insert into person (name, age, adress, income) values (?, ?, ?, ?)");
prepStmt.setString(1, korisnik.getName());
prepStmt.setInt(2, korisnik.getAge());
prepStmt.setString(3, korisnik.getAdress());
prepStmt.setInt(4, korisnik.getIncome());
ResultSet rs = prepStmt.executeQuery();
None of these work and I don't know why and how to do it properly.
Here is the whole code.
package javaapplication7;
import java.sql.PreparedStatement;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.util.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.*;
public class Main extends JFrame {
klik klik = new klik();
Handler handler = new Handler();
Korisnik korisnik = null;
List<Korisnik> korisnik_lista = new ArrayList();
public Color silver = new Color(192, 192, 192);
public JPanel bar, prozor, prikaz;
public JLabel x, minimize, title, id, name, age, adress, income;
public JTextArea korisnici;
public JButton sviKorisnici, poGodinama, izmenaPoID, brisanjePoID, unosNovog;
public JTextField inputID, inputName, inputAge, inputAdress, inputIncome;
public JScrollPane scroll;
public Main() {
bar = new JPanel();
bar.setLayout(null);
bar.setBounds(0, 0, 600, 25);
bar.setBackground(silver);
add(bar);
prozor = new JPanel();
prozor.setLayout(null);
prozor.setBounds(0, 20, 600, 400);
prozor.setBackground(Color.WHITE);
add(prozor);
prikaz = new JPanel(new BorderLayout());
prikaz.setLayout(null);
prikaz.setBounds(10, 20, 380, 150);
prozor.add(prikaz);
x = new JLabel("X");
x.setBounds(580, 0, 10, 20);
x.setFont(new Font("Arial", Font.BOLD, 14));
x.addMouseListener(klik);
bar.add(x);
minimize = new JLabel("_");
minimize.setBounds(555, 0, 10, 15);
minimize.setFont(new Font("Arial", Font.BOLD, 14));
minimize.setForeground(Color.BLACK);
minimize.addMouseListener(klik);
bar.add(minimize);
title = new JLabel("Assignment");
title.setBounds(20, 2, 100, 20);
bar.add(title);
sviKorisnici = new JButton("All Users");
sviKorisnici.setBounds(420, 20, 120, 30);
sviKorisnici.addActionListener(handler);
prozor.add(sviKorisnici);
poGodinama = new JButton("Find via Age");
poGodinama.setBounds(420, 70, 120, 30);
poGodinama.addActionListener(handler);
prozor.add(poGodinama);
izmenaPoID = new JButton("Change via ID");
izmenaPoID.setBounds(420, 120, 120, 30);
prozor.add(izmenaPoID);
brisanjePoID = new JButton("Delete via ID");
brisanjePoID.setBounds(420, 170, 120, 30);
prozor.add(brisanjePoID);
unosNovog = new JButton("Add New User");
unosNovog.setBounds(420, 220, 120, 30);
prozor.add(unosNovog);
korisnici = new JTextArea();
korisnici.setBounds(0, 0, 380, 150);
korisnici.setEditable(false);
prikaz.add(korisnici);
scroll = new JScrollPane(korisnici);
scroll.setBounds(0, 0, 380, 150);
prikaz.add(scroll);
id = new JLabel("ID:");
id.setBounds(10, 200, 40, 20);
prozor.add(id);
inputID = new JTextField();
inputID.setBounds(10, 220, 140, 20);
prozor.add(inputID);
name = new JLabel("Name:");
name.setBounds(200, 200, 40, 20);
prozor.add(name);
inputName = new JTextField();
inputName.setBounds(200, 220, 140, 20);
prozor.add(inputName);
age = new JLabel("Age:");
age.setBounds(10, 250, 40, 20);
prozor.add(age);
inputAge = new JTextField();
inputAge.setBounds(10, 270, 140, 20);
prozor.add(inputAge);
adress = new JLabel("Adress:");
adress.setBounds(200, 250, 50, 20);
prozor.add(adress);
inputAdress = new JTextField();
inputAdress.setBounds(200, 270, 140, 20);
prozor.add(inputAdress);
income = new JLabel("Income:");
income.setBounds(10, 300, 140, 20);
prozor.add(income);
inputIncome = new JTextField();
inputIncome.setBounds(10, 320, 140, 20);
prozor.add(inputIncome);
initComponents();
}
public static void main(String[] args) {
Main main = new Main();
}
class klik extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if (e.getSource() == x) {
System.exit(0);
} else if (e.getSource() == minimize) {
setState(JFrame.ICONIFIED);
}
}
}
class Handler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sviKorisnici) {
korisnik_lista.removeAll(korisnik_lista);
korisnici.setText("");
try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "traktor123");) {
Statement st = conn.createStatement();
st.executeQuery("select id, name, age, adress, income from person");
ResultSet rs = st.getResultSet();
while (rs.next()) {
korisnik = new Korisnik(rs.getInt("id"), rs.getString("name"), rs.getInt("age"), rs.getString("adress"), rs.getInt("income"));
korisnik_lista.add(korisnik);
}
} catch (SQLException ex) {
System.out.println("Error in database connection: \n" + ex.getMessage());
}
}
for (Korisnik kor : korisnik_lista) {
korisnici.append(kor.toString());
System.out.println(kor);
}
if (e.getSource() == poGodinama) {
korisnik_lista.removeAll(korisnik_lista);
korisnici.setText("");
try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "traktor123");) {
if(inputAge == null){
korisnici.setText("Nije unesen broj godina");
}
else{
int godine = Integer.parseInt(inputAge.getText());
String sqlStmt = "select * from person where age = ?";
PreparedStatement prepStmt;
prepStmt = conn.prepareStatement(sqlStmt);
prepStmt.setInt(1, godine);
ResultSet rs = prepStmt.executeQuery();
while (rs.next()) {
korisnik = new Korisnik(rs.getInt("id"), rs.getString("name"), rs.getInt("age"), rs.getString("adress"), rs.getInt("income"));
korisnik_lista.add(korisnik);
}
}
} catch (SQLException ex) {
System.out.println("Error in database connection: \n" + ex.getMessage());
}
for (Korisnik kor : korisnik_lista) {
korisnici.append(kor.toString());
System.out.println(kor);
}
}
if (e.getSource() == izmenaPoID) {
try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "traktor123");) {
int id = Integer.parseInt(inputID.getText());
String name = inputName.getText();
int age = Integer.parseInt(inputAge.getText());
String adress = inputAdress.getText();
int income = Integer.parseInt(inputIncome.getText());
String sqlStmt = "update person set name = ?, godine = ?, adress = ?, income = ? where id = ?";
PreparedStatement prepStmt;
prepStmt = conn.prepareStatement(sqlStmt);
prepStmt.setString(1, name);
prepStmt.setInt(2, age);
prepStmt.setString(3, adress);
prepStmt.setInt(4, income);
prepStmt.setInt(5, id);
prepStmt.executeUpdate();
} catch (SQLException ex) {
System.out.println("Error in database connection: \n" + ex.getMessage());
}
}
if (e.getSource() == brisanjePoID) {
try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "traktor123");) {
int id = Integer.parseInt(inputID.getText());
String sqlStmt = "delete from person where id = ?";
PreparedStatement prepStmt;
prepStmt = conn.prepareStatement(sqlStmt);
prepStmt.setInt(1, id);
prepStmt.executeUpdate();
} catch (SQLException ex) {
System.out.println("Error in database connection: \n" + ex.getMessage());
}
}
if (e.getSource() == unosNovog) {
try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "traktor123");) {
String name = inputName.getText();
int age = Integer.parseInt(inputAge.getText());
String adress = inputAdress.getText();
int income = Integer.parseInt(inputIncome.getText());
korisnik = new Korisnik(name,age,adress,income);
PreparedStatement prepStmt;
prepStmt = conn.prepareStatement("insert into person (name, age, adress, income) values (?, ?, ?, ?)");
prepStmt.setString(1, korisnik.getName());
prepStmt.setInt(2, korisnik.getAge());
prepStmt.setString(3, korisnik.getAdress());
prepStmt.setInt(4, korisnik.getIncome());
prepStmt.executeUpdate();
} catch (SQLException ex) {
System.out.println("Error in database connection: \n" + ex.getMessage());
}
}
}
}
void initComponents() {
this.setUndecorated(true);
this.setLayout(null);
this.setSize(600, 400);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
executeQuery()
Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.
executeUpdate()
Executes the SQL statement in this PreparedStatement object, which must be an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement.
In your case use executeUpdate() see the doc here

JLabel and JTextField don't appper in the swing form

Iwould like to create a form using java eclipse. The problem is i cannot obtain the total added JLabel and JTextField.this is my code:
class gestiontache extends JFrame{
JFrame f;
JPanel p1, p2, p3;
JTabbedPane tp;
JLabel l1, l2, l3,l4,l5;
JComboBox tf3categor;
JComboBox tf4Affiliation;
JComboBox tf5montant;
JTextField tf1, tf2;
JScrollPane sp1;
JButton savebtn, resetbtn, editbtn;
private static String FILE = "c:/temp/DocumentPdf.pdf";
private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
Font.BOLD);
private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.NORMAL, BaseColor.RED);
private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
Font.BOLD);
private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD);
gestiontache() {
f = new JFrame("Form");
GridLayout lay1= new GridLayout(12, 2);
GridLayout lay2= new GridLayout(5, 2);
p1 = new JPanel(lay1);
p2 = new JPanel(lay2);
lay1.setHgap(5); //Cinq pixels d'espace entre les colonnes (H comme Horizontal)
lay1.setVgap(5); //Cinq pixels d'espace entre les lignes (V comme Vertical)
lay2.setHgap(5);
lay2.setVgap(5);
tp = new JTabbedPane();
l1 = new JLabel("Nom");
l2 = new JLabel("Prénom");
l3 = new JLabel("Catégorie");
l4 = new JLabel("Affiliation");
l5 = new JLabel("Montant à payer");
tf1 = new JTextField(12);
tf2 = new JTextField(12);
tf3categor = new JComboBox( new String[] { "Medecin", "Technicien", "Pharmacien","Autre" });
tf4Affiliation =new JComboBox( new String[] { "K", "T", "Sf","Gab","Toze","Med","Tat","Na","B","G","Si","Ga","Ke","Kr" });
tf5montant = new JComboBox( new String[] { "15 Dinars", "30 Dinars"});
savebtn = new JButton(" Ajouter ");
resetbtn = new JButton(" Annuler");
editbtn = new JButton(" Imprimer");
p1.add(l1);
p1.add(tf1);
p1.add(l2);
p1.add(tf2);
p1.add(l3);
p1.add(tf3categor);
p1.add(l4);
p1.add(tf4Affiliation);
p1.add(l5);
p1.add(tf5montant);
p1.add(savebtn);
p1.add(resetbtn);
p2.add(l1);
p2.add(tf1);
p2.add(l2);
p2.add(tf2);
p2.add(editbtn);
resetbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
clear();
}
});
savebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String nom, prenom,categorie, affiliation, montant;
nom = tf1.getText();
prenom = tf2.getText();
categorie=(String) tf3categor.getSelectedItem();
affiliation=(String) tf4Affiliation.getSelectedItem();
montant=(String) tf5montant.getSelectedItem();
String url = "jdbc:mysql://localhost:3306/seminaire";
String userid = "root";
String password = "";
try {
Connection connection = DriverManager.getConnection(url,
userid, password);
Statement st = connection.createStatement();
if (nom != "" && prenom != ""&& categorie!= ""&& affiliation!= ""&& montant!= "") {
st.executeUpdate("insert into participant values('" + nom
+ "','" + prenom + "','" + categorie + "','"+affiliation+"','"+montant+"')");
JOptionPane.showMessageDialog(null,"Données insérées avec succès");
clear();
} else {
JOptionPane.showMessageDialog(null, "merci de saisir vos données");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
editbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String nom, prenom,categorie, affiliation, montant;
nom = tf1.getText();
prenom = tf2.getText();
String url = "jdbc:mysql://localhost:3306/seminaire";
String userid = "root";
String password = "";
try {
Connection connection = DriverManager.getConnection(url,
userid, password);
Statement st = connection.createStatement();
if (nom != "" && prenom != "") {
ResultSet rs= st.executeQuery("SELECT * FROM participant
WHERE nom=nom && prenom=prenom");
while (rs.next())
{
String nm = rs.getString("nom");
String prnm = rs.getString("prenom");
String cat = rs.getString("categorie");
String afl=rs.getString("affiliation");
String mnt=rs.getString("montant");
// print the results
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(FILE));
//open
document.open();
Paragraph p = new Paragraph();
p.add("Reçu");
p.setAlignment(Element.ALIGN_CENTER);
document.add(p);
Paragraph p2 = new Paragraph();
p2.add(nm); //no alignment
document.add(p2);
Font f = new Font();
f.setStyle(Font.BOLD);
f.setSize(8);
document.add(new Paragraph("This is my paragraph 3", f));
//close
document.close();
System.out.println("Done");
} catch (FileNotFoundException | DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
else {
JOptionPane.showMessageDialog(null, "merci de saisir vos données");
}
}
catch (Exception e)
{
System.err.println(e.getMessage());
}
}});
}
void dis() {
f.getContentPane().add(tp);
tp.addTab("Ajouter participant", p1);
tp.addTab("Imprimer attestation", p2);
f.setSize(500, 400);
f.setVisible(true);
f.setResizable(true);
}
void clear()
{
tf1.setText("");
tf2.setText("");
tf3categor.setSelectedItem("");
tf4Affiliation.setSelectedItem("");
tf5montant.setSelectedItem("");
}
public static void main(String z[]) {
gestiontache data = new gestiontache();
data.dis();
}
}
`
The problem here is the JLabel and JTextField(nom, prenom)don't appear in the form in order to insert or select from database. Have any idea how can i correct it please. Thank you
p2.add(l1);
p2.add(tf1);
p2.add(l2);
p2.add(tf2);
These above fields are added in both p1(Tab1) and p2(Tab2) Panels.
Thats why its not showing.
You must create seperate controls for both p1 and p2 panels. Don't reuse same controls in two panels.
For example:
l7 = new JLabel("Normal");
p2.add(l7);

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

jFrame not opening correctly or showing contents

so I have a school project I need help on!
So I am doing a 'task force schedule' app as my major project for this year (Grade 11, south africa) and I am stuck. I have an login system that logs into the database fine, then I have a "check in station" class called CheckIn which has a button that should open a table showing all the people working in a given station at that time if they are checked in.
So far the table only pulls data from the database of everyone that is in the station, regardless of whether they are here or not, but that is not the issue.
The issue is that if I start the class Welcome (the station called 'Welcome') it runs fine showing the following image:
but when I try to open the welcome class from within the program (so I click on the quick link in the CheckIn class, it does this:
The code for the Welcome class works fine, I got it through a tutorial I copied from youtube, but it works 100%.
Is there something I am doing wrong???
Any advice would be greatly appreciated.
Thanks Josh
Here is the code, by the way :P :
CheckIn class:
package co.za.gecko.inked.crm;
import java.awt.EventQueue;
public class CheckIn extends JFrame {
String u = (String) Login.cbxUsername.getSelectedItem();
static ArrayList<String> firstNames = new ArrayList<>();
JLabel lblHello = new JLabel("Hello, "+u.toString());
JLabel lblClock = new JLabel("");
static JComboBox cbxCIFirstName = new JComboBox();
static JComboBox cbxCILastName = new JComboBox();
// to add checked in people to pCI stands for personCheckedIn
static ArrayList<String> pCI = new ArrayList<>();
// all jLabels for the stations
JLabel lblWelcome = new JLabel("Welcome: 0");
JLabel lblScanning = new JLabel("Scanning: 0");
JLabel lblChecking = new JLabel("Checking: 0");
JLabel lblRunners = new JLabel("Runners: 0");
JLabel lblWrapping = new JLabel("Wrapping: 0");
JLabel lblFirstAid = new JLabel("First Aid: 0");
JLabel lblVolunteers = new JLabel("Volunteers: 0");
// all counters for the stations
int cWelcome = 0;
int cScanning = 0;
int cChecking = 0;
int cRunners = 0;
int cWrapping = 0;
int cFirstAid = 0;
int cVolunteers = 0;
// all stations with volunteer id in station
static ArrayList<String> inWelcomeStation = new ArrayList<>();
ArrayList<String> inScanningStation = new ArrayList<>();
ArrayList<String> inCheckingStation = new ArrayList<>();
ArrayList<String> inRunnersStation = new ArrayList<>();
ArrayList<String> inWrappingStation = new ArrayList<>();
ArrayList<String> inFirstAidStation = new ArrayList<>();
ArrayList<String> inVolunteersStation = new ArrayList<>();
JLabel lblCIStation = new JLabel("Welcome");
JLabel lblCITime = new JLabel("10:00");
/**
* Launch the application.
*/
public static void main(String[] args) throws Exception{
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CheckIn frame = new CheckIn();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws Exception
*/
public CheckIn() throws Exception{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1024, 768);
getContentPane().setLayout(null);
lblHello.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblHello.setBounds(10, 11, 182, 25);
getContentPane().add(lblHello);
lblClock.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblClock.setBounds(941, 11, 57, 25);
getContentPane().add(lblClock);
JLabel lblDay = new JLabel("Day 1");
lblDay.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblDay.setBounds(863, 11, 57, 25);
getContentPane().add(lblDay);
cbxCIFirstName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
cbxCILastName.removeAllItems();
getLastNames();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
cbxCIFirstName.addInputMethodListener(new InputMethodListener() {
public void caretPositionChanged(InputMethodEvent arg0) {
}
public void inputMethodTextChanged(InputMethodEvent arg0) {
}
});
cbxCIFirstName.setEditable(true);
cbxCIFirstName.setBounds(307, 106, 330, 20);
getContentPane().add(cbxCIFirstName);
cbxCILastName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
updateCheckInData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
cbxCILastName.setBounds(307, 163, 330, 20);
getContentPane().add(cbxCILastName);
JLabel lblFirstName = new JLabel("First Name");
lblFirstName.setBounds(307, 93, 73, 14);
getContentPane().add(lblFirstName);
JLabel lblLastName = new JLabel("Last Name");
lblLastName.setBounds(307, 149, 73, 14);
getContentPane().add(lblLastName);
JLabel lblStation = new JLabel("Station");
lblStation.setBounds(647, 93, 73, 14);
getContentPane().add(lblStation);
JLabel lblTime = new JLabel("Time");
lblTime.setBounds(647, 149, 73, 14);
getContentPane().add(lblTime);
lblCIStation.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblCIStation.setBounds(647, 102, 136, 25);
getContentPane().add(lblCIStation);
lblCITime.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblCITime.setBounds(647, 159, 136, 25);
getContentPane().add(lblCITime);
JButton btnCheckIn = new JButton("Check In");
btnCheckIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
checkedIn();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnCheckIn.setBounds(759, 117, 110, 55);
getContentPane().add(btnCheckIn);
JSeparator separator = new JSeparator();
separator.setBounds(52, 220, 900, 2);
getContentPane().add(separator);
lblWelcome.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblWelcome.setBounds(85, 254, 161, 25);
getContentPane().add(lblWelcome);
lblScanning.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblScanning.setBounds(85, 290, 161, 25);
getContentPane().add(lblScanning);
lblChecking.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblChecking.setBounds(85, 326, 161, 25);
getContentPane().add(lblChecking);
lblRunners.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblRunners.setBounds(452, 326, 161, 25);
getContentPane().add(lblRunners);
lblWrapping.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblWrapping.setBounds(452, 290, 161, 25);
getContentPane().add(lblWrapping);
lblFirstAid.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblFirstAid.setBounds(452, 254, 161, 25);
getContentPane().add(lblFirstAid);
lblVolunteers.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblVolunteers.setBounds(724, 254, 161, 25);
getContentPane().add(lblVolunteers);
JSeparator separator_1 = new JSeparator();
separator_1.setBounds(52, 383, 900, 2);
getContentPane().add(separator_1);
JLabel lblQuickLinks = new JLabel("Quick Links");
lblQuickLinks.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblQuickLinks.setBounds(85, 413, 161, 25);
getContentPane().add(lblQuickLinks);
JButton btnOster = new JButton("Roster");
btnOster.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnOster.setBounds(85, 451, 116, 55);
getContentPane().add(btnOster);
JButton btnVolunteerInfo = new JButton("Volunteer Info");
btnVolunteerInfo.setBounds(211, 451, 116, 55);
getContentPane().add(btnVolunteerInfo);
JButton btnSearch = new JButton("Search");
btnSearch.setBounds(337, 451, 116, 55);
getContentPane().add(btnSearch);
JButton btnWelcome = new JButton("Welcome");
btnWelcome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnWelcome.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
checkStation("Welcome");
Welcome openWelcome = new Welcome();
openWelcome.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
btnWelcome.setBounds(85, 526, 116, 55);
getContentPane().add(btnWelcome);
JButton btnScanning = new JButton("Scanning");
btnScanning.setBounds(211, 526, 116, 55);
getContentPane().add(btnScanning);
JButton btnChecking = new JButton("Checking");
btnChecking.setBounds(337, 526, 116, 55);
getContentPane().add(btnChecking);
JButton btnFirstAid = new JButton("First Aid");
btnFirstAid.setBounds(463, 526, 116, 55);
getContentPane().add(btnFirstAid);
JButton btnWrapping = new JButton("Wrapping");
btnWrapping.setBounds(589, 526, 116, 55);
getContentPane().add(btnWrapping);
JButton btnRunners = new JButton("Runners");
btnRunners.setBounds(715, 526, 116, 55);
getContentPane().add(btnRunners);
JButton btnVolunteers = new JButton("Volunteers");
btnVolunteers.setBounds(842, 526, 116, 55);
getContentPane().add(btnVolunteers);
JButton btnCheckOut = new JButton("Check Out");
btnCheckOut.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
try {
checkOut();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnCheckOut.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
try {
checkOut();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnCheckOut.setBounds(124, 117, 110, 55);
getContentPane().add(btnCheckOut);
getFirstNames();
}
public static void getFirstNames() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `first_name` FROM volunteers");
ResultSet result = statement.executeQuery();
cbxCIFirstName.setToolTipText("Select a first name");
cbxCIFirstName.setEditable(true);
cbxCIFirstName.addItem("Please select a first name");
while(result.next()){
if(firstNames.contains(result.getString(1)) != true){
firstNames.add(result.getString(1));
}
}
for(int i=0; i<firstNames.size(); i++){
cbxCIFirstName.addItem(firstNames.get(i));
}
}
public static void getLastNames() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `last_name` FROM volunteers WHERE `first_name` = '" + cbxCIFirstName.getSelectedItem() + "'");
ResultSet result = statement.executeQuery();
cbxCILastName.setToolTipText("Select a last name");
cbxCILastName.setEditable(true);
int rowcount = 0;
if (result.last()) {
rowcount = result.getRow();
result.beforeFirst(); // not rs.first() because the rs.next() below will move on, missing the first element
}
if(rowcount > 1){
cbxCILastName.addItem("Please select a last name");
}
while(result.next()){
cbxCILastName.addItem(result.getString(1));
}
}
public void checkedIn() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `volunteer_id` FROM volunteers WHERE `first_name` = '" + cbxCIFirstName.getSelectedItem() + "' AND `last_name` = '" + cbxCILastName.getSelectedItem() + "'");
ResultSet result = statement.executeQuery();
while(result.next()){
// checks if volunteer id is already in the array, ie: already checked in
if(pCI.contains(result.getString(1))){
JOptionPane.showMessageDialog(null, "Sorry, this volunteer is already logged in!");
} else {
// add volunteer id to array list
pCI.add(result.getString(1));
System.out.println(pCI);
addToLabel(result.getString(1));
getStationInfo(result.getString(1));
}
}
}
public void addToLabel(String user_id) throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `station` FROM volunteers WHERE `volunteer_id` = '" + user_id + "'");
ResultSet result = statement.executeQuery();
while(result.next()){
String stat = result.getString(1);
switch (stat) {
case "welcome":
case "Welcome":
cWelcome++;
lblWelcome.setText("Welcome: " + cWelcome);
break;
case "scanning":
case "Scanning":
cScanning++;
lblScanning.setText("Scanning: " + cScanning);
break;
case "checking":
case "Checking":
cChecking++;
lblChecking.setText("Checking: " + cChecking);
break;
case "runners":
case "Runners":
cRunners++;
lblRunners.setText("Runners: " + cRunners);
break;
case "wrapping":
case "Wrapping":
cWrapping++;
lblWrapping.setText("Wrapping: " + cWrapping);
break;
case "firstaid":
case "Firstaid":
case "firstAid":
case "FirstAid":
cFirstAid++;
lblFirstAid.setText("First Aid: " + cFirstAid);
break;
case "volunteers":
case "Volunteers":
cVolunteers++;
lblVolunteers.setText("Volunteers: " + cVolunteers);
break;
default:
break;
}
}
}
public void updateCheckInData() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `station`, `time` FROM volunteers WHERE `first_name` = '" + cbxCIFirstName.getSelectedItem() + "' AND `last_name` = '" + cbxCILastName.getSelectedItem() + "'");
ResultSet result = statement.executeQuery();
while(result.next()){
lblCIStation.setText(result.getString(1));
String station = lblCIStation.getText();
station = station.substring(0, 1).toUpperCase() + station.substring(1);
lblCIStation.setText(station);
lblCITime.setText(result.getString(2));
}
}
public void checkOut() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `volunteer_id` FROM volunteers WHERE `first_name` = '" + cbxCIFirstName.getSelectedItem() + "' AND `last_name` = '" + cbxCILastName.getSelectedItem() + "'");
ResultSet result = statement.executeQuery();
while(result.next()){
pCI.remove(result.getString(1));
System.out.println(pCI);
removeFromLabel(result.getString(1));
}
}
public void removeFromLabel(String user_id) throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `station` FROM volunteers WHERE `volunteer_id` = '" + user_id + "'");
ResultSet result = statement.executeQuery();
while(result.next()){
String stat = result.getString(1);
switch (stat) {
case "welcome":
case "Welcome":
cWelcome--;
lblWelcome.setText("Welcome: " + cWelcome);
break;
case "scanning":
case "Scanning":
cScanning--;
lblScanning.setText("Scanning: " + cScanning);
break;
case "checking":
case "Checking":
cChecking--;
lblChecking.setText("Checking: " + cChecking);
break;
case "runners":
case "Runners":
cRunners--;
lblRunners.setText("Runners: " + cRunners);
break;
case "wrapping":
case "Wrapping":
cWrapping--;
lblWrapping.setText("Wrapping: " + cWrapping);
break;
case "firstaid":
case "Firstaid":
case "firstAid":
case "FirstAid":
cFirstAid--;
lblFirstAid.setText("First Aid: " + cFirstAid);
break;
case "volunteers":
case "Volunteers":
cVolunteers--;
lblVolunteers.setText("Volunteers: " + cVolunteers);
break;
default:
break;
}
}
}
public void checkStation(String station) throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `volunteer_id` FROM volunteers WHERE `station` = '" + station + "'");
ResultSet result = statement.executeQuery();
while(result.next()){
switch (station) {
case "Welcome":
case "welcome":
break;
case "Scanning":
case "scanning":
break;
case "Checking":
case "checking":
break;
case "Runners":
case "runners":
break;
case "Wrapping":
case "wrapping":
break;
case "FirstAid":
case "Firstaid":
case "firstAid":
case "firstaid":
break;
case "Volunteers":
case "volunteers":
break;
default:
break;
}
}
}
public void getStationInfo(String id) throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `first_name`, `last_name`, `time`, `station` FROM volunteers WHERE `volunteer_id` = '" + id + "'");
ResultSet result = statement.executeQuery();
String vid = id;
List vidd = new ArrayList<>(Arrays.asList(vid));
while(result.next()){
switch (result.getString(4)) {
case "Welcome":
case "welcome":
inWelcomeStation = (ArrayList<String>) vidd;
break;
case "Scanning":
case "scanning":
inScanningStation = (ArrayList<String>) vidd;
break;
case "Checking":
case "checking":
inCheckingStation = (ArrayList<String>) vidd;
break;
case "Runners":
case "runners":
inRunnersStation = (ArrayList<String>) vidd;
break;
case "Wrapping":
case "wrapping":
inWrappingStation = (ArrayList<String>) vidd;
break;
case "FirstAid":
case "Firstaid":
case "firstAid":
case "firstaid":
inFirstAidStation = (ArrayList<String>) vidd;
break;
case "Volunteers":
case "volunteers":
inVolunteersStation = (ArrayList<String>) vidd;
break;
default:
break;
}
}
}
}
and the Welcome class:
package co.za.gecko.inked.crm;
import java.awt.BorderLayout;
public class Welcome extends JFrame {
static Object[][] databaseInfo;
static Object[] columns = {"first name", "last name", "cellphone", "time", "station"};
static ResultSet rows;
static ResultSetMetaData metaData;
static DefaultTableModel dTableModel = new DefaultTableModel(databaseInfo, columns) {
// public Class getColumnClass(int column){
// Class returnValue;
// if((column >= 0) && (column < getColumnCount())){
// returnValue = getValueAt(0, column).getClass();
// } else {
// returnValue = Object.class;
// }
// return returnValue;
// }
};
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setBounds(0, 0, 1024, 768);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
Statement sqlState = conn.createStatement();
String selectStuff = "SELECT `first_name`, `last_name`, `cellphone`, `time` FROM volunteers";
rows = sqlState.executeQuery(selectStuff);
Object[] tempRow;
while(rows.next()){
tempRow = new Object[]{rows.getString(1), rows.getString(2), rows.getString(3), rows.getString(4)};
dTableModel.addRow(tempRow);
}
// get column name ?
// metaData = rows.getMetaData();
// int numOfCol = metaData.getColumnCount();
//
// columns = new String[numOfCol];
//
// for(int i=1; i<= numOfCol; i++){
// columns[i] = metaData.getColumnName(i);
// }
} catch (ClassNotFoundException ex) {
// TODO Auto-generated catch block
System.out.println(ex.getMessage());
} catch (SQLException ex) {
// TODO Auto-generated catch block
System.out.println(ex.getMessage());
}
JTable table = new JTable(dTableModel);
table.setRowHeight(table.getRowHeight() + 10); // change row height
table.setFont(new Font("Serif", Font.PLAIN, 20)); // change font
table.setAutoCreateRowSorter(true); // sort table
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // change column resize
TableColumn col1 = table.getColumnModel().getColumn(0); // change column width
col1.setPreferredWidth(100);
TableColumn tc = table.getColumn("cellphone");
CenterTableCellRenderer centerRenderer = new CenterTableCellRenderer();
tc.setCellRenderer(centerRenderer);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(800, 500);
frame.setVisible(true);
}
}
(so I click on the quick link in the CheckIn class,
You should be using an ActionListener (not a MouseListener) to listen for a click on a button.
The basic structure for your code should be:
JFrame frame = new JFrame();
...
frame.add(scrollPane...);
frame.pack() //or frame.setSize(...)
frame.pack()
frame.setVisible(true);
That is you should only display the frame AFTER you have added all the component to the frame. Right now your code makes the frame visible before you add any components.
Also, you should not be using static variables. Those variables should be instance variables in your welcome class.
The above comments are general in nature and not the cause of your real problem.
The problem is that your Welcome class doesn't have a constructor.
When you execute the Welcome class through the JVM then the main() method is invoked which is where you create the frame and all the components.
When you invoke the Welcome class through your other program the empty constructor for your Welcome class is executed. This code does nothing. Since your class extends JFrame all you see is an empty frame.
So to solve your problem you basically need to move all the code related to build a frame into the constructor of your Welcome class.

Categories