I have created a runnable jar file for a login page. The folder where the runnable jar is saved also contains a folder named "lib" which contains files for images (used for icons and stuff) and an sqlite database file (which contains usernames and passwords).
When I execute the runnable jar and click on the login button after entering the username and password, it successfully executes. But when I convert the same jar file to exe and run it, the images from lib folder get loaded, but nothing happens when I click the login button. It seems as if the exe file is not connecting to the sqlite database in the "lib" folder.
Following is the code:
package db;
import javax.swing.*;
public class One extends JFrame {
private JButton btn_login = new JButton("LOGIN");
private JPanel panel = new JPanel();
private JTextField tf_user;
Connection conn=null;
PreparedStatement pst = null;
ResultSet rs= null;
private JPasswordField tf_pass;
public static void main(String[] args) {
One frameTabel = new One();
}
One(){
super("LOGIN PAGE");
setTitle("NETWORK TRACKER - LOGIN");
setBackground(new Color(70, 130, 180));
btn_login.setFont(new Font("Tahoma", Font.PLAIN, 8));
btn_login.setBackground(new Color(102, 205, 170));
btn_login.setForeground(Color.WHITE);
btn_login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:lib/login.sqlite");
String sql = "SELECT * from table12 where Username=? and Password=?";
pst = conn.prepareStatement(sql);
pst.setString(1, tf_user.getText());
pst.setString(2, tf_pass.getText());
rs = pst.executeQuery();
if(rs.next()){
rs.close();
pst.close();
setVisible(false);
Display dp = new Display();
dp.setVisible(true);
dp.setSize(300, 300);
} else{
JOptionPane.showMessageDialog(null, "Username or Password is not correct");
}
} catch (Exception e){
System.out.println("Error: "+e);
} finally{
try{
rs.close();
pst.close();
} catch (Exception e){
}
}
}
});
btn_login.setBounds(342,153,58,20);
panel.setBackground(new Color(112, 128, 144));
panel.add(btn_login);
setupLog();
getContentPane().add(panel);
JLabel lbl_title = new JLabel("NETWORK TRACKER LOGIN PAGE ");
lbl_title.setBackground(new Color(47, 79, 79));
lbl_title.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_title.setForeground(Color.LIGHT_GRAY);
lbl_title.setFont(new Font("HelveticaNeue", Font.PLAIN, 16));
lbl_title.setBounds(0, 252, 457, 23);
panel.add(lbl_title);
JLabel lbl_user = new JLabel("USERNAME");
lbl_user.setFont(new Font("HelveticaNeue", Font.PLAIN, 12));
lbl_user.setForeground(new Color(255, 250, 250));
lbl_user.setBounds(263, 93, 69, 14);
panel.add(lbl_user);
tf_user = new JTextField();
tf_user.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
tf_user.setBounds(342, 90, 105, 22);
panel.add(tf_user);
tf_user.setColumns(10);
JLabel lbl_pass = new JLabel("PASSWORD");
lbl_pass.setFont(new Font("HelveticaNeue", Font.PLAIN, 12));
lbl_pass.setForeground(new Color(255, 250, 250));
lbl_pass.setBounds(263, 129, 69, 14);
panel.add(lbl_pass);
tf_pass = new JPasswordField();
tf_pass.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
tf_pass.setBounds(342, 123, 105, 20);
panel.add(tf_pass);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon("lib/login.png"));
label.setBounds(0, 11, 236, 240);
panel.add(label);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void setupLog(){
setSize(473,313);
setLocation(500,280);
panel.setLayout (null);
}
}
Related
I'm new to JAVA, and trying to build a login and registration form which connected to MySQL local database. I've searched many instructions to connect my JAVA to MySQL, but it ends up with error. I think I have some problem with actionEvent() and actionPerformed(ActionEvent e) methods. I want to make it like when I register a new account, I want to save that user data into MySQL local database. Can someone help me to solve my problem? Here is my JAVA coding.
package login_register_form;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.*;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.JComboBox;
public class RegisterPage implements ActionListener{
// frame
JFrame frame;
// Options of position input
String[] position = {"Admin", "Manager", "Assistant"};
// inputs
JTextField firstName = new JTextField();
JTextField lastName = new JTextField();
JTextField userName = new JTextField();
JTextField email = new JTextField();
JPasswordField password = new JPasswordField();
JPasswordField confirmPW = new JPasswordField();
JComboBox positionComboBox = new JComboBox(position);
// labels
JLabel firstnameLabel = new JLabel("First Name");
JLabel lastnameLabel = new JLabel("Last Name");
JLabel usernameLabel = new JLabel("User Name");
JLabel passwordLabel = new JLabel("Password");
JLabel confirmPWLabel = new JLabel("Re-Password");
JLabel emailLabel = new JLabel("Email");
JLabel positionLabel = new JLabel("Position");
JLabel returnLoginLabel = new JLabel("Return to Login Page");
// buttons
JButton registerButton = new JButton("Register");
JButton cancelButton = new JButton("Cancel");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RegisterPage window = new RegisterPage();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application. Calling methods from constructor
*/
public RegisterPage() {
createWindow();
initialize();
actionEvent();
actionPerformed(null);
}
/**
* Create a main window
*/
public void createWindow() {
frame = new JFrame();
frame.setTitle("Registration Page");
frame.getContentPane().setBackground(Color.GRAY);
frame.setBounds(100, 100, 1113, 806);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
// panel: orange colored background
JPanel panel = new JPanel();
panel.setBackground(new Color(255,165,0,200));
panel.setBounds(300, 150, 500, 472);
frame.getContentPane().add(panel);
panel.setLayout(null);
// label: scaled background
JLabel background = new JLabel("");
background.setBounds(6, 6, 1100, 772);
ImageIcon icon = new ImageIcon(this.getClass().getResource("/background.jpg"));
Image img = icon.getImage();
Image imgScale = img.getScaledInstance(background.getWidth(), background.getHeight(), Image.SCALE_SMOOTH);
ImageIcon scaledIcon = new ImageIcon(imgScale);
background.setIcon(scaledIcon);
frame.getContentPane().add(background);
// title: "Register Page"
JLabel registerPage = new JLabel("Register Page");
registerPage.setFont(new Font("Lucida Grande", Font.BOLD, 19));
registerPage.setBounds(182, 40, 135, 29);
panel.add(registerPage);
// input: first name
firstName.setBounds(145, 76, 210, 32);
panel.add(firstName);
firstName.setColumns(10);
// input: last name
lastName.setBounds(145, 120, 210, 32);
panel.add(lastName);
lastName.setColumns(10);
// input: user name
userName.setBounds(145, 164, 210, 32);
panel.add(userName);
userName.setColumns(10);
// input: password
password.setBounds(145, 208, 210, 32);
panel.add(password);
// input: confirm password
confirmPW.setBounds(145, 252, 210, 32);
panel.add(confirmPW);
// input: emailLabel
email.setBounds(145, 296, 210, 32);
panel.add(email);
email.setColumns(10);
// input: position
positionComboBox.setBounds(145, 340, 210, 32);
panel.add(positionComboBox);
// label: first name
firstnameLabel.setBounds(36, 84, 85, 16);
panel.add(firstnameLabel);
// label: last name
lastnameLabel.setBounds(36, 128, 85, 16);
panel.add(lastnameLabel);
// label: user name
usernameLabel.setBounds(36, 172, 85, 16);
panel.add(usernameLabel);
// label: password
passwordLabel.setBounds(36, 216, 85, 16);
panel.add(passwordLabel);
// label: re-password
confirmPWLabel.setBounds(36, 260, 85, 16);
panel.add(confirmPWLabel);
// label: emailLabel
emailLabel.setBounds(36, 304, 85, 16);
panel.add(emailLabel);
// label: position
positionLabel.setBounds(36, 347, 101, 16);
panel.add(positionLabel);
// Label: create a new account
returnLoginLabel.setBounds(182, 450, 138, 16);
panel.add(returnLoginLabel);
returnLoginLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
frame.setVisible(false);
new LoginPage();
}
});
// button: cancel
cancelButton.setBounds(109, 400, 117, 40);
panel.add(cancelButton);
// button: register
registerButton.setBounds(275, 400, 117, 40);
panel.add(registerButton);
}
public void actionEvent() {
// Adding action listener to buttons
registerButton.addActionListener(this);
cancelButton.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == registerButton) {
try {
//Creating Connection Object
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase","root", "root");
//Prepared Statement
PreparedStatement Pstatement = connection.prepareStatement("insert into user values(?,?,?,?,?,?,?)");
// Specifying the values of it's parameter
Pstatement.setString(1, firstName.getText());
Pstatement.setString(2, lastName.getText());
Pstatement.setString(3, userName.getText());
Pstatement.setString(4, password.getText());
Pstatement.setString(5, confirmPW.getText());
Pstatement.setString(6, email.getText());
Pstatement.setString(7, positionComboBox.getSelectedItem().toString());
//Checking for the password match
if (password.getText().equals(confirmPW.getText())) {
// Executing query
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null, "Data Registered Successfully");
// go back to login page if registered successfully
frame.setVisible(false);
new LoginPage();
}
else {
JOptionPane.showMessageDialog(null, "Password did not match");
// Clearing confirm password fields
confirmPW.setText("");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (e.getSource() == cancelButton) {
// Clearing Fields
firstName.setText("");
lastName.setText("");
userName.setText("");
password.setText("");
confirmPW.setText("");
email.setText("");
positionComboBox.setSelectedItem("Admin");
}
}
}
Here is my MySQL coding:
create database myDatabase;
use myDatabase;
create table user(
FIRSTNAME varchar(20),
LASTNAME varchar(20),
USERNAME varchar(20) not null,
PASSWRD varchar(20),
CONFIRMPASSWORD varchar(20),
EMAIL varchar(20),
POSITION varchar(20) );
Please tell me, if I'm doing anything wrong. Thank you! 🙏
You missed the line Class.forName("com.mysql.jdbc.Driver");
For the line ("jdbc:mysql://localhost:3306/myDatabase","root", "root"), you should check if the password is root. if there is no password, then it should be like this:
if (e.getSource() == registerButton) {
try {
Class.forName("com.mysql.jdbc.Driver");
//Creating Connection Object
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase","root", "");
//Prepared Statement
PreparedStatement Pstatement = connection.prepareStatement("insert into user values(?,?,?,?,?,?,?)");
// Specifying the values of it's parameter
Pstatement.setString(1, firstName.getText());
Pstatement.setString(2, lastName.getText());
Pstatement.setString(3, userName.getText());
Pstatement.setString(4, password.getText());
Pstatement.setString(5, confirmPW.getText());
Pstatement.setString(6, email.getText());
Pstatement.setString(7, positionComboBox.getSelectedItem().toString());
//Checking for the password match
if (password.getText().equals(confirmPW.getText())) {
// Executing query
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null, "Data Registered Successfully");
// go back to login page if registered successfully
frame.setVisible(false);
new LoginPage();
}
else {
JOptionPane.showMessageDialog(null, "Password did not match");
// Clearing confirm password fields
confirmPW.setText("");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
I am doing a project on library management in java using swing on eclipse. When I click on the login button nothing happens. The mysql jdbc driver is loaded and I am getting the connection but no label appears. Please tell me what to do. Here is my code.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
public class Loginscreen implements ActionListener {
JFrame logframe;
JButton bt;
JLabel lid, lpass, lmsg;
JTextField tid;
JPasswordField pass;
JPanel p1;
Font ft, ft2;
Connection conn;
public Loginscreen() {
logframe = new JFrame("Login");
logframe.setSize(1366, 720);
logframe.setVisible(true);
lid = new JLabel("User ID");
lpass = new JLabel("Password");
lmsg = new JLabel();
ft = new Font("Arial", Font.BOLD, 30);
ft2 = new Font("Arial", Font.PLAIN, 20);
tid = new JTextField();
pass = new JPasswordField();
p1 = new JPanel();
bt = new JButton("Login");
logframe.add(p1);
p1.setLayout(null);
p1.setBackground(new Color(160, 82, 45));//Background Color Set
lid.setBounds(450, 200, 500, 30);
p1.add(lid);
lid.setFont(ft);
tid.setBounds(650, 200, 200, 30);
p1.add(tid);
tid.setFont(ft2);
lpass.setBounds(450, 300, 500, 30);
p1.add(lpass);
lpass.setFont(ft);
pass.setBounds(650, 300, 200, 30);
p1.add(pass);
bt.setBounds(600, 430, 100, 50);
p1.add(bt);
bt.setFont(new Font("Segoe Script", Font.BOLD, 22));
bt.setBackground(new Color(173, 216, 230));
lmsg.setBounds(450, 510, 500, 30);
p1.add(lmsg);
bt.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == bt) {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_lib", "root", "admin");
String i = tid.getText();//get the user id
char[] pwd = pass.getPassword();//get the password
String spwd = new String(pwd);//converting char to string
String query = "select * from tbl_user where id=? and password=?";
PreparedStatement p = conn.prepareStatement(query);
p.setString(1, i);
p.setString(2, spwd);
ResultSet rs = p.executeQuery();
int count = 0;
while (rs.next()) {
count = count + 1;
}
if (count == 1) {
lmsg.setText("Invalid User ID or Password");
} else {
lmsg.setText("Invalid User ID or Password");
}
rs.close();
conn.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
}
I guess you dont set the text when it succeeds.
Also make sure
while(rs.next())
{
count=count+1;
}
terminates.
Also secure your query against SQL-Injection (just realized this)
For these kinds of debugging problems I recommend UnitTesting (basically just test how far the program goes, how long it takes, if it terminates etc).
Also before you post a question, do us a favor to add comments and format the GUI-stuff properly...it looks horrible :/
EDIT:
if(count==1)
{
lmsg.setText("Invalid User ID or Password");
}
else
{
lmsg.setText("Invalid User ID or Password");
}
Does not make sense to me... Whatever happens you return an error
I am trying to get the student information by providing the roll number and medium from db. The swing application executed without any error but when I enter the roll no and medium then its going to the "Student not Found" else loop.
I guess the problems with get string or the prepared statements.kindly help me to find out the issue.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
public class Searchdb extends JFrame implements ActionListener {
//Initializing Components
JLabel lb,lbd,lb1, lb2, lb3, lb5;
JTextField tf1, tf2,tf3,tf5,tfd;
JButton btn;
//Creating Constructor for initializing JFrame components
Searchdb() {
//Providing Title
super("Fetching Roll Information");
lb5 = new JLabel("Roll Number:");
lb5.setBounds(20, 20, 100, 20);
tf5 = new JTextField(20);
tf5.setBounds(130, 20, 200, 20);
lbd = new JLabel("Date:");
lbd.setBounds(20, 50, 100, 20);
tfd = new JTextField(20);
tfd.setBounds(130, 50, 200, 20);
btn = new JButton("Submit");
btn.setBounds(50, 50, 100, 20);
btn.addActionListener(this);
lb = new JLabel("Fetching Student Information From Database");
lb.setBounds(30, 80, 450, 30);
lb.setForeground(Color.black);
lb.setFont(new Font("Serif", Font.PLAIN, 12));
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
lb1 = new JLabel("Name:");
lb1.setBounds(20, 120, 100, 20);
tf1 = new JTextField(50);
tf1.setBounds(130, 120, 200, 20);
lb2 = new JLabel("Fathername:");
lb2.setBounds(20, 150, 100, 20);
tf2 = new JTextField(100);
tf2.setBounds(130, 150, 200, 20);
lb3 = new JLabel("State:");
lb3.setBounds(20, 180, 100, 20);
tf3 = new JTextField(50);
tf3.setBounds(130, 180, 200, 20);
setLayout(null);
//Add components to the JFrame
add(lb5);
add(tf5);
add(lbd);
add(tfd);
add(btn);
add(lb);
add(lb1);
add(tf1);
add(lb2);
add(tf2);
add(lb3);
add(tf3);
//Set TextField Editable False
tf1.setEditable(false);
tf2.setEditable(false);
tf3.setEditable(false);
}
public void actionPerformed(ActionEvent e) {
//Create DataBase Coonection and Fetching Records
try {
String str = tf5.getText();
Datestri = tfd.getText();//Getting the unable to convert String to Date error
System.out.println(str);
System.out.println(stri);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#//host:port/servicename","username","password");
PreparedStatement st = con.prepareStatement("select Name,Fathername,State from student_db where roll_number=? and medium=?");
System.out.println(st);
st.setString(1, str);
st.setDate(2, stri);
//Excuting Query
ResultSet rs = st.executeQuery();
System.out.println(rs);
if (rs.next()) {
String s = rs.getString(1);
String s1 = rs.getString(2);
String s2 = rs.getString(3);
//Sets Records in TextFields.
tf1.setText(s);
tf2.setText(s1);
tf3.setText(s2);
} else {
JOptionPane.showMessageDialog(null, "Student not Found");
}
//Create Exception Handler
} catch (Exception ex) {
System.out.println(ex);
}
}
//Running Constructor
public static void main(String args[]) {
new Searchdb();
}
}
sql query:
select Name,Fathername,State from student_db where roll_number='1441' and medium='2016-12-18';
Results:
Name Fathername State
SA TH YA
Suppose if i am not passing the "Stri" variable in the query i am getting the results.
I have updated the code below and its working fine, when i checked the database type for the medium column name it is varchar2(40), so i decided to use the getString only.
Getting proper response with this code,
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
public class Searchdb extends JFrame implements ActionListener {
//Initializing Components
JLabel lb,lbd,lb1, lb2, lb3, lb5;
JTextField tf1, tf2,tf3,tf5,tfd;
JButton btn;
//Creating Constructor for initializing JFrame components
Searchdb() {
//Providing Title
super("Fetching Roll Information");
lb5 = new JLabel("Roll Number:");
lb5.setBounds(20, 20, 100, 20);
tf5 = new JTextField(20);
tf5.setBounds(130, 20, 200, 20);
lbd = new JLabel("Date:");
lbd.setBounds(20, 50, 100, 20);
tfd = new JTextField(20);
tfd.setBounds(130, 50, 200, 20);
btn = new JButton("Submit");
btn.setBounds(50, 50, 100, 20);
btn.addActionListener(this);
lb = new JLabel("Fetching Student Information From Database");
lb.setBounds(30, 80, 450, 30);
lb.setForeground(Color.black);
lb.setFont(new Font("Serif", Font.PLAIN, 12));
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
lb1 = new JLabel("Name:");
lb1.setBounds(20, 120, 100, 20);
tf1 = new JTextField(50);
tf1.setBounds(130, 120, 200, 20);
lb2 = new JLabel("Fathername:");
lb2.setBounds(20, 150, 100, 20);
tf2 = new JTextField(100);
tf2.setBounds(130, 150, 200, 20);
lb3 = new JLabel("State:");
lb3.setBounds(20, 180, 100, 20);
tf3 = new JTextField(50);
tf3.setBounds(130, 180, 200, 20);
setLayout(null);
//Add components to the JFrame
add(lb5);
add(tf5);
add(lbd);
add(tfd);
add(btn);
add(lb);
add(lb1);
add(tf1);
add(lb2);
add(tf2);
add(lb3);
add(tf3);
//Set TextField Editable False
tf1.setEditable(false);
tf2.setEditable(false);
tf3.setEditable(false);
}
public void actionPerformed(ActionEvent e) {
//Create DataBase Coonection and Fetching Records
try {
String str = tf5.getText();
String stri = tfd.getText();
System.out.println(str);
System.out.println(stri);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#//host:port/servicename","username","password");
String str1 ="select Name,Fathername,State from student_db where roll_number='"+str+"' and medium='"+stri+"'";
PreparedStatement st = con.prepareStatement(str1);
System.out.println(st);
st.setString(1, str);
st.setString(2, stri);
//Excuting Query
ResultSet rs = st.executeQuery();
System.out.println(rs);
if (rs.next()) {
String s = rs.getString(1);
String s1 = rs.getString(2);
String s2 = rs.getString(3);
//Sets Records in TextFields.
tf1.setText(s);
tf2.setText(s1);
tf3.setText(s2);
} else {
JOptionPane.showMessageDialog(null, "Student not Found");
}
//Create Exception Handler
} catch (Exception ex) {
System.out.println(ex);
}
}
//Running Constructor
public static void main(String args[]) {
new Searchdb();
}
}
I am new to the world of Java and sqlite database. I was trying out some codes about loading data from a database into a tabular view using java in eclipse. Now, here is the thing, when my data loads from the database, i want to add an extra column which contains a checkbox(unchecked). Can someone suggest me how do i implement it? Please note that when i run the code, it works absolutely fine and shows no error....I am able to see all the records in my table without any error. Just want an unchecked checkbox to be added to each row so that when i click on it, i can do something. Thats my goal..
Here is what i tried so far.. I have two classes namely:-
1. sqliteConnection.java(which is for connection )
2. employeeinfo.java class which is for loading the data from the database into a table and other functionalities.
import java.sql.*;
import javax.swing.*;
public class sqliteConnection {
Connection conn = null;
public static Connection dbConnector()
{
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\user\\Downloads\\Documents\\MyJavaProjects\\Phone\\Employee.sqlite");
JOptionPane.showMessageDialog(null, "Connection Succesful");
return conn;
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
public sqliteConnection() {
// TODO Auto-generated constructor stub
}
}
employeeinfo.java --
import java.awt.BorderLayout;
public class employeeinfo extends JFrame {
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
employeeinfo frame = new employeeinfo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
Connection connection = null;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
public employeeinfo() {
connection = sqliteConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 842, 457);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblJframe = new JLabel("Jframe2");
lblJframe.setBounds(47, 37, 46, 14);
contentPane.add(lblJframe);
JButton btnLoad = new JButton("Load");
btnLoad.addActionListener(new ActionListener() {
PreparedStatement pat;
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select eid,Name,Surname,Age from EmployeeInfo ";
pat = connection.prepareStatement(query);
ResultSet rs = pat.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e)
{
}
}
});
btnLoad.setBounds(104, 33, 89, 23);
contentPane.add(btnLoad);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(429, 48, 370, 232);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
JLabel lblName = new JLabel("EID");
lblName.setBounds(10, 98, 46, 21);
contentPane.add(lblName);
textField = new JTextField();
textField.setBounds(107, 99, 126, 20);
contentPane.add(textField);
textField.setColumns(10);
JLabel lblName_1 = new JLabel("Name");
lblName_1.setBounds(10, 154, 46, 14);
contentPane.add(lblName_1);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(107, 151, 126, 20);
contentPane.add(textField_1);
JLabel lblSurname = new JLabel("Surname");
lblSurname.setBounds(10, 204, 46, 14);
contentPane.add(lblSurname);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(104, 201, 126, 20);
contentPane.add(textField_2);
JLabel lblAge = new JLabel("Age");
lblAge.setBounds(10, 278, 46, 14);
contentPane.add(lblAge);
textField_3 = new JTextField();
textField_3.setColumns(10);
textField_3.setBounds(104, 275, 126, 20);
contentPane.add(textField_3);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
PreparedStatement pat;
try {
String query = "insert into EmployeeInfo(EID,name,surname,age) values(?,?,?,?)";
pat = connection.prepareStatement(query);
pat.setString(1, textField.getText());
pat.setString(2, textField_1.getText());
pat.setString(3, textField_2.getText());
pat.setString(4, textField_3.getText());
pat.execute();
JOptionPane.showMessageDialog(null, "Data Saved successfully");
pat.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
btnSave.setBounds(72, 349, 89, 23);
contentPane.add(btnSave);
JButton btnClear = new JButton("Clear");
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
textField_1.setText("");
textField_2.setText("");
textField_3.setText("");
}
});
btnClear.setBounds(206, 349, 89, 23);
contentPane.add(btnClear);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
String query="Update EmployeeInfo set EID='"+textField.getText()+"',Name='"+textField_1.getText()+"'"
+",Surname='"+textField_2.getText()+"',Age='"+textField_3.getText()+"'where EID='"+textField.getText()+"'";
// JOptionPane.showMessageDialog(null, query);
PreparedStatement pst=connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Data Saved successfully");
pst.close();
}
catch(Exception f)
{
f.printStackTrace();
}
}
});
btnUpdate.setBounds(323, 349, 89, 23);
contentPane.add(btnUpdate);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
String query="delete from EmployeeInfo where EID='"+textField.getText()+"'";
// JOptionPane.showMessageDialog(null, query);
PreparedStatement pst=connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Data deleted successfully");
pst.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
btnDelete.setBounds(453, 349, 89, 23);
contentPane.add(btnDelete);
}
}
My suggestion is you first go through this article, it's a very simpler way of loading data from ResultSet to DefaultTableModel. After this you have to make some small changes like, you have to add another column heading to the Vector of columnNames and add a column for check boxes. Then when you process each row from the ResultSet you need to add a Boolean value to the row Vector with a checkbox .
I am trying to create a register system for my MySQL database. I have a Java form that I created, in which the user inserts a username, password, and their email. I take that infromation and store it in a variable accordingly. The MySQL connection code works, and it does insert a new row, but the information is blank on the MySQL page. Am I doing someting wrong?
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JPasswordField passwordField;
private static Connection con;
private static PreparedStatement st;
private static int rs;
String username;
String password;
String email;
private JTextField textField_1;
String insertTableSQL = "INSERT INTO `users`" + "(username, password, email) VALUES" + "(?,?,?)";
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main() {
setResizable(false);
setTitle("Barrage : Login / Register");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 350, 200);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Username: ");
lblNewLabel.setBounds(60, 25, 68, 20);
contentPane.add(lblNewLabel);
JLabel lblPassword = new JLabel("Password: ");
lblPassword.setBounds(60, 59, 68, 20);
contentPane.add(lblPassword);
textField = new JTextField();
username = textField.getText();
textField.setBounds(138, 22, 120, 26);
contentPane.add(textField);
textField.setColumns(10);
passwordField = new JPasswordField();
password = passwordField.getText();
passwordField.setBounds(138, 56, 120, 26);
contentPane.add(passwordField);
JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/barrage", "root", "");
st = con.prepareStatement(insertTableSQL);
st.setString(1, username);
st.setString(2, password);
st.setString(3, email);
st.executeUpdate();
} catch(Exception e) {
e.printStackTrace();
}
}
});
btnRegister.setBounds(119, 138, 89, 23);
contentPane.add(btnRegister);
JLabel lblEmail = new JLabel("E-mail: ");
lblEmail.setBounds(60, 96, 68, 20);
contentPane.add(lblEmail);
textField_1 = new JTextField();
email = textField_1.getText();
textField_1.setBounds(138, 93, 120, 26);
contentPane.add(textField_1);
textField_1.setColumns(10);
}
}
You need to call the various fields' getText() method in your ActionListener so that you get the values after the user has entered them.
As it stands now you get the initial values prior to any user interaction.
You need to set the values of username u.a. in the moment where you you call the actionPerformed method.
Right now you set the value when creating the GUI. At that moment they are null. They are not "linked", they just take the value that the controls return at that time. If the controls getText() result changes, your variables do not get updated.