I have 2 class .1 for GUI.1 from others.
LoginUser.java
package login;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import database.DatabaseConnection;
public class LoginUser{
public int doLogin(String username, String password) throws Exception
{
int level =0;
DatabaseConnection databaseConnection = new DatabaseConnection();
Connection con = databaseConnection.getConnection();
String sql ="select level from staff where username=? and password=?";
PreparedStatement ps =con.prepareStatement(sql);
//no 1 and two refer to ? at String sql =...
//Tukar String pada int
ps.setString(1, username);
//int iPassword = Integer.parseInt(password);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if(rs.next())
{
level = rs.getInt(1);
}
//must close all connection
rs.close();ps.close();con.close();
return level;
}
public static void main(String[] args) {
//test sama ada login berjaya atau tak?
LoginUser lgn = new LoginUser();
try {
int level =lgn.doLogin("1008", "test123");
System.out.println("Access Level : "+level);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Another one is for GUI class
LoginInterface.java
package login;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPasswordField;
import java.awt.Color;
import login.LoginUser;
public class LoginInterface {
private JFrame frame;
private JTextField txtStaffID;
private JPasswordField txtPassword;
/**
* Launch the application.
*/
public static void login() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LoginInterface window = new LoginInterface();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public LoginInterface() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 678, 421);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblStaffId = new JLabel("Username :");
lblStaffId.setForeground(Color.BLACK);
lblStaffId.setFont(new Font("Times New Roman", Font.PLAIN, 16));
lblStaffId.setBounds(108, 158, 89, 23);
frame.getContentPane().add(lblStaffId);
txtStaffID = new JTextField();
txtStaffID.setBounds(207, 160, 200, 23);
frame.getContentPane().add(txtStaffID);
txtStaffID.setColumns(10);
JLabel lblPassword = new JLabel("Password :");
lblPassword.setForeground(Color.BLACK);
lblPassword.setFont(new Font("Times New Roman", Font.PLAIN, 16));
lblPassword.setBounds(108, 192, 101, 49);
frame.getContentPane().add(lblPassword);
JButton btnLogIn = new JButton("LOGIN");
btnLogIn.setBackground(new Color(0, 206, 209));
btnLogIn.setForeground(new Color(0, 0, 0));
btnLogIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LoginUser lgn = new LoginUser();
try {
String username =txtStaffID.getText();
#SuppressWarnings("deprecation")
String password = txtPassword.getText();
int level =lgn.doLogin(username, password);
if(level == 1)
{
JOptionPane.showMessageDialog(null, "You successfully login");
}
else
{
JOptionPane.showMessageDialog(null, "Your password or username incorrect");
}
System.out.println("Access Level : "+level);
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, "Please insert your username and password");
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnLogIn.setFont(new Font("Times New Roman", Font.PLAIN, 16));
btnLogIn.setBounds(283, 272, 113, 34);
frame.getContentPane().add(btnLogIn);
txtPassword = new JPasswordField();
txtPassword.setBounds(207, 208, 200, 20);
frame.getContentPane().add(txtPassword);
}
}
I use PHPmyadmin and XAMPP as for database.Please help me :(
I cant run LoginInterface.I dont know why.Is something wrong on my eclipse luna?
Its only display for running LoginUser.java
You never called LoginInterface.login(); Just add it to your main method.
Related
Here I have created a JTable and surround it with JScrollPane. I have created an update and refresh button so that I can refresh and update the values in the data set. But the problem is with the refresh button whenever I click the button it appears the data more than one time. Like I have 10 data set after updating the name when I refresh the button it is showing again 10 data means a total of 10+10=20 same types of data.
package insertData;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import com.mysql.cj.xdevapi.Statement;
import com.sun.jdi.connect.spi.Connection;
//import com.sun.tools.sjavac.pubapi.PubApi;
import java.awt.Color;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.awt.event.ActionEvent;
import javax.swing.JSplitPane;
public class Table_formate {
private JFrame frame;
private JTextField nametextField;
private JTextField idtextField;
private JTextField textFieldname;
private JTextField textFieldid;
private JTable table;
//Connection connection;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Table_formate window = new Table_formate();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Table_formate() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 539);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
nametextField = new JTextField();
nametextField.setBounds(140, 11, 152, 37);
frame.getContentPane().add(nametextField);
nametextField.setColumns(10);
idtextField = new JTextField();
idtextField.setColumns(10);
idtextField.setBounds(140, 68, 152, 37);
frame.getContentPane().add(idtextField);
JButton btnNewButton = new JButton("Submit");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");//load driver
java.sql.Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root"); //Establish connection
System.out.println("sucess");
String drop="insert into student values(?,?) ";
java.sql.PreparedStatement ps=((java.sql.Connection) connection).prepareStatement(drop);
//System.out.println(ps);
ps.setInt(1, Integer.parseInt(idtextField.getText()));
ps.setString(2, nametextField.getText());
System.out.println("id="+idtextField.getText()+" "+"name="+nametextField.getText());
ps.executeUpdate();
ps.close();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(324, 36, 89, 46);
frame.getContentPane().add(btnNewButton);
JLabel lblNewLabel = new JLabel("Name:");
lblNewLabel.setBounds(27, 11, 76, 37);
frame.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Id:");
lblNewLabel_1.setBounds(27, 68, 76, 37);
frame.getContentPane().add(lblNewLabel_1);
JButton Refreshbtn = new JButton("Refresh");
Refreshbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
DefaultTableModel tableModel=(DefaultTableModel) table.getModel();
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root");
java.sql.Statement stmt=((java.sql.Connection) connection).createStatement();
System.out.println("connection sucessful");
ResultSet rs= ((java.sql.Statement) stmt).executeQuery("select * from student order by id");
//PreparedStatement ps=connection.prepareStatement("select * from student order by id");
while ( rs.next()) {
String name=rs.getString("name");
int id=rs.getInt("id");
System.out.println(id+ "name="+name);
tableModel.addRow(new Object[] {id,name});
}
stmt.close();
rs.close();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
Refreshbtn.setBounds(122, 139, 89, 30);
frame.getContentPane().add(Refreshbtn);
JLabel lblNewLabel_2 = new JLabel("Name:");
lblNewLabel_2.setBounds(27, 395, 76, 37);
frame.getContentPane().add(lblNewLabel_2);
JLabel lblNewLabel_1_1 = new JLabel("Id:");
lblNewLabel_1_1.setBounds(27, 452, 76, 37);
frame.getContentPane().add(lblNewLabel_1_1);
textFieldname = new JTextField();
textFieldname.setColumns(10);
textFieldname.setBounds(140, 395, 152, 37);
frame.getContentPane().add(textFieldname);
textFieldid = new JTextField();
textFieldid.setColumns(10);
textFieldid.setBounds(140, 452, 152, 37);
frame.getContentPane().add(textFieldid);
JButton btnUpdat = new JButton("update");
btnUpdat.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String drop="update student set name=? where id=?";
try {
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root");
PreparedStatement ps=((java.sql.Connection) connection).prepareStatement(drop);
ps.setString(1, textFieldname.getText());
ps.setInt(2, Integer.parseInt(textFieldid.getText()));
ps.executeUpdate();
System.out.println("Record updated");
ps.close();
Refreshbtn.doClick();
} catch (ClassNotFoundException | SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnUpdat.setBounds(324, 420, 89, 46);
frame.getContentPane().add(btnUpdat);
JButton btnEdit = new JButton("Edit");
btnEdit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel tableModel=(DefaultTableModel) table.getModel();
tableModel.fireTableDataChanged();
int row=table.getSelectedRow();
String name=(String) tableModel.getValueAt(row, 1);
String id=(String) tableModel.getValueAt(row, 0).toString();
textFieldid.setText(id);
textFieldname.setText(name);
}
});
btnEdit.setBounds(231, 139, 89, 30);
frame.getContentPane().add(btnEdit);
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"id", "name"
}
));
table.setBounds(10, 203, 414, 167);
frame.getContentPane().add(table);
}
}
As #Abra mentioned, just clear the contents of your DefaultTableModel when refreshing and before adding the new data as follows:
DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
tableModel.setRowCount(0);
tableModel.setColumnCount(0);
After cleaning the model, populate it again (in this example, adding some random user):
model.addColumn("id");
model.addColumn("Name");
Vector<String> userName = new Vector<>();
userName.add(user);
model.addRow(userName);
I have two JFrame windows one for the login and the second for the welcome. Now I want to present the Firstname and the Lastname of the connected user near to the hello in the welcome screen.
I tried many things but none of them worked so I'm asking for you help. I just started to learn GUI:
The login code:
import java.awt.EventQueue;
import java.sql.*;
import javax.swing.*;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login {
private JFrame frame;
private JLabel MainLogo;
String Firstname=null;
String Lastname=null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
Connection connected = null;
private JTextField UsernameFiled;
private JPasswordField passwordField;
public Login() {
initialize();
connected = DBConnection.DBconnector();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 560, 256);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("UserName: ");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 20));
lblNewLabel.setBounds(160, 11, 140, 50);
frame.getContentPane().add(lblNewLabel);
JLabel lblPassword = new JLabel("PassWord: ");
lblPassword.setFont(new Font("Tahoma", Font.BOLD, 20));
lblPassword.setBounds(160, 72, 140, 40);
frame.getContentPane().add(lblPassword);
JButton Loginbtn = new JButton("Login");
Loginbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "Select * from Users where nickname=? and password=?";
PreparedStatement pst = connected.prepareStatement(query);
pst.setString(1, UsernameFiled.getText());
pst.setString(2, passwordField.getText());
ResultSet res = pst.executeQuery();
Firstname = res.getString("Firstname");
Lastname = res.getString("Lastname");
int c=0;
while(res.next()) {
c++;
}
if(c == 0) {
JOptionPane.showMessageDialog(null, "You didnt put any username or password!");
}
else if(c == 1) {
JOptionPane.showMessageDialog(null, "Hello to you, " + Firstname +" "+ Lastname);
frame.dispose();
UserPage UserFrame = new UserPage();
UserFrame.setVisible(true);
}else if( c > 1) {
JOptionPane.showMessageDialog(null, "Duplicate Username and Password");
}else {
JOptionPane.showMessageDialog(null, "Username and Password are inncorect...Try agian!");
}
pst.close();
res.close();
}catch(Exception LoginError) {
JOptionPane.showMessageDialog(null, LoginError);
}
}
});
Loginbtn.setFont(new Font("Tahoma", Font.BOLD, 20));
Loginbtn.setBounds(160, 148, 186, 40);
frame.getContentPane().add(Loginbtn);
UsernameFiled = new JTextField();
UsernameFiled.setFont(new Font("Tahoma", Font.BOLD, 16));
UsernameFiled.setBounds(310, 28, 186, 25);
frame.getContentPane().add(UsernameFiled);
UsernameFiled.setColumns(10);
passwordField = new JPasswordField();
passwordField.setFont(new Font("Tahoma", Font.BOLD, 16));
passwordField.setBounds(310, 84, 186, 25);
frame.getContentPane().add(passwordField);
MainLogo = new JLabel("");
Image imgs = new ImageIcon(this.getClass().getResource("/login.png")).getImage();
MainLogo.setIcon(new ImageIcon(imgs));
MainLogo.setBounds(10, 11, 128, 128);
frame.getContentPane().add(MainLogo);
}
}
The Welcome Code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class UserPage extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UserPage frame = new UserPage();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
Connection connected=null;
private JTable table;
public UserPage() {
connected=DBConnection.DBPreconnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 576, 410);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton bntLoadData = new JButton("Show Users Data");
bntLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "Select ID,Age,Password,Firstname,Lastname from users";
PreparedStatement pst = connected.prepareStatement(query);
ResultSet res = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(res));
} catch (Exception Error) {
Error.printStackTrace();
}
}
});
JLabel lblNewLabel = new JLabel("Hello, " + "The Username name");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 18));
lblNewLabel.setBounds(10, 11, 280, 19);
contentPane.add(lblNewLabel);
bntLoadData.setFont(new Font("Tahoma", Font.BOLD, 20));
bntLoadData.setBounds(162, 102, 238, 23);
contentPane.add(bntLoadData);
table = new JTable();
table.setBounds(28, 136, 508, 221);
contentPane.add(table);
}
}
In your code, you does not seem to load the username or password of the logged in user at the welcome frame. Either you will have to pass that from the login frame or you will have to re-query the database and get firstname and lastname.
I suggest, simply pass the firstname and lastname from welcome screen via constructor.
In successful login, simply pass the name in the constructor: Login code addition:
} else if(c == 1) {
JOptionPane.showMessageDialog(null, "Hello to you, " + Firstname +" "+ Lastname);
frame.dispose();
UserPage UserFrame = new UserPage( Firstname, Lastname );
UserFrame.setVisible(true);
}
In the welcome frame, add a constructor to handle this:
public UserPage(String loggedInFirstName, String loggedInLastName){
// your remaining code
JLabel lblNewLabel = new JLabel("Hello, " + loggedInFirstName + " " + loggedInLastName );
// your remaining code.
}
A approach like this might work for your case and don't forget to mark the answer as accepted if this works for you
so I am using eclipse and mysql to create a login interface. The interface worked fine as a shell, so without being connected to the databse, and now I finally got it connected to the database but I'm running into the problem of linking it to another application upon successful login.
So for the shell of it I just gave the code a single username/password combo to proceed to the next part of the interface, but if I want to have the link work upon successful login in general, where do I place it in the code?
My code:
package project_files;
import javax.swing.JFrame;
import javax.swing.JToolBar;
import project_files.registration_test;
import project_files.root_login;
import project_files.gui_interface;
import project_files.video_interface;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JSeparator;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
public class login_sys {
private JFrame frame;
private JTextField txtUsername;
private JPasswordField txtPassword;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
login_sys window = new login_sys();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public login_sys() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(200, 200, 523, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel LabelLogin = new JLabel("Login Page");
LabelLogin.setBounds(209, 12, 100, 15);
frame.getContentPane().add(LabelLogin);
JLabel LabelUsername = new JLabel("Username");
LabelUsername.setBounds(61, 68, 92, 17);
frame.getContentPane().add(LabelUsername);
JLabel LabelPassword = new JLabel("Password");
LabelPassword.setBounds(61, 133, 66, 15);
frame.getContentPane().add(LabelPassword);
txtUsername = new JTextField();
txtUsername.setBounds(244, 68, 124, 19);
frame.getContentPane().add(txtUsername);
txtUsername.setColumns(10);
txtPassword = new JPasswordField();
txtPassword.setBounds(244, 131, 124, 19);
frame.getContentPane().add(txtPassword);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
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 user where Email = '" +txtUsername.getText()+"' and Password ='" +txtPassword.getText().toString()+"'";
ResultSet rs=stmt.executeQuery(sql);
if(rs.next())
JOptionPane.showMessageDialog(null, "Login Successfully...");
else
JOptionPane.showMessageDialog(null, "Incorrect username and password...");
con.close();
} catch(Exception e) {System.out.print (e);}
String password = txtPassword.getText();
String username = txtUsername.getText();
if(password.contains("pass1234") && username.contains("root")){
txtPassword.setText(null);
txtUsername.setText(null);
root_login info = new root_login();
root_login.main(null);
}
else
{
if(password.contains("pass1234") && username.contains("john#gmail.com")){
txtPassword.setText(null);
txtUsername.setText(null);
JOptionPane.showMessageDialog(null, "Login Successful", "Login Warning", JOptionPane.WARNING_MESSAGE);
video_interface info = new video_interface();
video_interface.main(null);
}
else
{
JOptionPane.showMessageDialog(null, "Invalid Login Details", "Login Error", JOptionPane.ERROR_MESSAGE);
txtPassword.setText(null);
txtUsername.setText(null);
}
}
}});
btnLogin.setBounds(23, 203, 130, 25);
frame.getContentPane().add(btnLogin);
JButton btnReset = new JButton("Reset");
btnReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
txtUsername.setText(null);
txtPassword.setText(null);
}
});
btnReset.setBounds(212, 203, 114, 25);
frame.getContentPane().add(btnReset);
JButton btnNewExit = new JButton("Exit");
btnNewExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFrame frmLogin_sys = new JFrame("Exit");
if (JOptionPane.showConfirmDialog(frmLogin_sys, "Confirm if you want to exit", "Login System",
JOptionPane.YES_NO_OPTION)== JOptionPane.YES_NO_OPTION) {
System.exit(0);
}
}
});
btnNewExit.setBounds(373, 203, 114, 25);
frame.getContentPane().add(btnNewExit);
JSeparator separator = new JSeparator();
separator.setBounds(12, 175, 499, 2);
frame.getContentPane().add(separator);
JSeparator separator_1 = new JSeparator();
separator_1.setBounds(12, 36, 499, 2);
frame.getContentPane().add(separator_1);
JButton btnCreateAccount = new JButton("Create Account");
btnCreateAccount.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
registration_test info = new registration_test();
registration_test.main(null);
}
});
btnCreateAccount.setBounds(135, 233, 265, 25);
frame.getContentPane().add(btnCreateAccount);
}
}
I was using (and it is still in my code currently)
if(password.contains("pass1234") && username.contains("john#gmail.com")){
txtPassword.setText(null);
txtUsername.setText(null);
JOptionPane.showMessageDialog(null, "Login Successful", "Login Warning", JOptionPane.WARNING_MESSAGE);
video_interface info = new video_interface();
video_interface.main(null);
to link a successful login to an additional application interface. Can i just
use
video_interface info = new video_interface();
video_interface.main(null);
as I have been doing? Where is the correct place to add this code? The second application location is imported at the beginning of my code.
If you change the constructor of the video_interface class to initialize and show the GUI components (as you're currently doing in the login_sys.initialize method), you'll be just fine with
video_interface info = new video_interface()
There should only be one static void main(String[] args) method in any Java program.
As a side note, Java conventionally uses camelCasing, (e.g. JFrame, JTextField) and if you adopt that convention your code will be easier to read.
I use SQLite. I have 2 JFrames. 1st is consists of table and "Load data", "Edit data". Click on Edit make the new, 2nd JFrame to appear. I want my table to be updated after I make some changes with a help of class Edit. How do I make it? One idea is to use ActionListener so that after I click save, delete or update buttons in JFrame2 method of Jframe 1, which stays for updating of the table(using query), is called. I have tried, but it does not work. I do not want the method of the 1 Jframe to be called in 2nd Jframe, I want this method to be called in 1st Jframe. What are possible solutions?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
import javax.swing.*;
public class Diary extends JFrame {
private JPanel contentPane;
JTable table;
private JButton btnLoadData;
public void refreshTabel(){
try {
String query = "select * from Diary";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Diary frame = new Diary();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Diary() {
setResizable(false);
connection = Main.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1250, 650);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(34, 58, 1182, 530);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
btnLoadData = new JButton("Load data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select * from Diary";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnLoadData.setBounds(33, 17, 117, 29);
contentPane.add(btnLoadData);
JButton btnAddData = new JButton("Edit");
btnAddData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddData nw = new AddData();
nw.addData();
refreshTabel();
}
});
btnAddData.setBounds(153, 17, 117, 29);
contentPane.add(btnAddData);
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.sun.glass.events.WindowEvent;
import net.proteanit.sql.DbUtils;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.awt.event.ActionEvent;
public class AddData extends JFrame {
private JPanel contentPane;
private JTextField Date;
private JTextField ExerciseName;
private JTextField Weight;
private JTextField Sets;
private JTextField Reps;
/**
* Launch the application.
* #return
*/
public static void addData() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddData frame = new AddData();
frame.setVisible(true);
frame.setAlwaysOnTop(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
private JTextField Exercise;
private JTextField N;
/**
* Create the frame.
*/
public AddData() {
setTitle("Edit");
setResizable(false);
connection = Main.dbConnector();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 465, 368);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblDate = new JLabel("Date");
lblDate.setBounds(29, 49, 61, 16);
contentPane.add(lblDate);
JLabel ExerciseLabel = new JLabel("Exercise");
ExerciseLabel.setBounds(29, 88, 90, 16);
contentPane.add(ExerciseLabel);
JLabel lblNewLabel_1 = new JLabel("Sets");
lblNewLabel_1.setBounds(29, 169, 61, 16);
contentPane.add(lblNewLabel_1);
JLabel lblReps = new JLabel("Reps");
lblReps.setBounds(29, 213, 61, 16);
contentPane.add(lblReps);
JLabel lblWeight = new JLabel("Weight");
lblWeight.setBounds(29, 126, 61, 16);
contentPane.add(lblWeight);
Date = new JTextField();
Date.setBounds(169, 56, 150, 26);
contentPane.add(Date);
Date.setColumns(10);
ExerciseName = new JTextField();
ExerciseName.setBounds(169, 60, 150, 26);
contentPane.add(ExerciseLabel);
ExerciseName.setColumns(10);
Weight = new JTextField();
Weight.setBounds(169, 132, 150, 26);
contentPane.add(Weight);
Weight.setColumns(10);
Sets = new JTextField();
Sets.setBounds(169, 170, 150, 26);
contentPane.add(Sets);
Sets.setColumns(10);
Reps = new JTextField();
Reps.setBounds(169, 208, 150, 26);
contentPane.add(Reps);
Reps.setColumns(10);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "insert into Diary (Date, Exercise, Weight, Sets, Reps) values (?,?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, Date.getText());
pst.setString(2, Exercise.getText());
pst.setString(3, Weight.getText());
pst.setString(4, Sets.getText());
pst.setString(5, Reps.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Saved");
pst.close();
} catch (Exception ea) {
ea.printStackTrace();
}
}
});
btnSave.setBounds(29, 261, 117, 29);
contentPane.add(btnSave);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "update Diary set N ='"+N.getText()+"', Exercise ='"+Exercise.getText()+"', Weight ='"+Weight.getText()+"', Sets ='"+Sets.getText()+"', Reps ='"+Reps.getText()+"' where N ='"+N.getText()+"' ";
PreparedStatement pst = connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Updated");
pst.close();
} catch (Exception ea) {
ea.printStackTrace();
}
}
});
btnUpdate.setBounds(176, 261, 117, 29);
contentPane.add(btnUpdate);
Exercise = new JTextField();
Exercise.setBounds(169, 94, 150, 26);
contentPane.add(Exercise);
Exercise.setColumns(10);
N = new JTextField();
N.setBounds(169, 18, 150, 26);
contentPane.add(N);
N.setColumns(10);
JLabel lblN = new JLabel("N");
lblN.setBounds(29, 23, 61, 16);
contentPane.add(lblN);
JButton Delete = new JButton("Delete");
Delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "delete from Diary where N = '"+N.getText()+"'";
PreparedStatement pst = connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Deleted");
pst.close();
} catch (Exception ea) {
ea.printStackTrace();
}
}
});
Delete.setBounds(305, 261, 117, 29);
contentPane.add(Delete);
}
}
Im trying to populate JTable with MySql data. Thing is when i run Login class, i receive message "java.SQLException: No value specified for parameter 2" and when i run JTable class I keep receiving java.lang.NullPointerException error. I have three classes : 1-Connection to DB:
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class javaconnect {
Connection conn = null;
public static Connection ConnecrDB() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb",
"root", "root");
JOptionPane.showMessageDialog(null, "Connected");
return con;
} catch (Exception e) {
System.out.println("ERROR: " + e.getMessage());
}
return null;
}
}
The second class is login frame:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.*;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class JFrameLogIn extends JFrame {
Connection conn =null;
ResultSet rs = null;
PreparedStatement pst = null;
private JPanel contentPane;
private JPasswordField txt_Password;
private JTextField txt_Username;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrameLogIn frame = new JFrameLogIn();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JFrameLogIn() {
conn=javaconnect.ConnecrDB();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 375, 214);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setFont(new Font("Tahoma", Font.BOLD, 13));
lblUsername.setBounds(126, 45, 80, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setFont(new Font("Tahoma", Font.BOLD, 13));
lblPassword.setBounds(126, 82, 69, 14);
contentPane.add(lblPassword);
txt_Password = new JPasswordField();
txt_Password.setBounds(218, 82, 109, 20);
contentPane.add(txt_Password);
txt_Username = new JTextField();
txt_Username.setBounds(216, 43, 111, 20);
contentPane.add(txt_Username);
txt_Username.setColumns(10);
JButton cmd_Login = new JButton("Login");
cmd_Login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String sql = "Select * from clients where username=? and password=?";
try{
pst = conn.prepareStatement(sql);
pst.setString(1, txt_Username.getText());
pst.setString(1, txt_Password.getText());
rs = pst.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Username and Password are correct");
}
else {
JOptionPane.showMessageDialog(null, "Username and Password are not correct");
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
});
cmd_Login.setBounds(218, 125, 80, 23);
contentPane.add(cmd_Login);
}
}
and the last one is JTable
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.sql.*;
import net.proteanit.sql.DbUtils;
public class JTable1 extends JFrame {
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
private JPanel contentPane;
private JTable table_Admins;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JTable1 frame = new JTable1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JTable1() {
conn = javaconnect.ConnecrDB();
UpdateTable ();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
table_Admins = new JTable();
table_Admins.setBounds(30, 28, 378, 54);
contentPane.add(table_Admins);
}
private void UpdateTable () {
try {
String sql = "SELECT *FROM menu";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
table_Admins.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
I am trying to figure out what is the problem but cannot find the solution. Connection works. I would really appreciate your help in fixing this error.
The second parameter in your PreparedStatment is not set. You should replace
pst.setString(1, txt_Password.getText());
with
pst.setString(2, txt_Password.getText());
Edit: Note that JPassword.getText() is deprecated meaning that you should no longer use it. getPassword() is provided in its place:
pst.setString(2, new String(txt_Password.getPassword()));
you can add a check to the code
rs = pst.executeQuery();
if (rs!=null){
if(rs.next()){
JOptionPane.showMessageDialog(null, "Username and Password are correct");
}
else {
JOptionPane.showMessageDialog(null, "Username and Password are not correct");
}
}
And Also in your JTable1 class
if (rs!=null)
table_Admins.setModel(DbUtils.resultSetToTableModel(rs));
private void UpdateTable () {
conn = javaconnect.ConnecrDB();// connection and query should be in same place
try {
String sql = "SELECT *FROM menu";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
table_Admins.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}