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
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 was trying to build this management system.
the login page is the main page if the user forgets their password then they can click on the forget password to change the password.
but,
whenever i call the forgot password from login frame, a small window opens rather than the coded window of forget page.
NOTE:the forget window runs fine when executed alone.
login page
`package hM_prac;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPasswordField;
import java.sql.*;
public class login extends JFrame implements ActionListener {
private JPanel contentPane;
private JTextField txtUsername;
private JPasswordField pwdwhatever;
JLabel lblNewLabel,lblNewLabel_1,lblNewLabel_2;
JButton btnForgotPassword ,btnSignUp,btnLogin;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
login frame = new login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection con;
PreparedStatement ps;
ResultSet rs;
/**
* Create the frame.
*/
public login() {
super("LOGIN");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 465, 300);
contentPane = new JPanel();
contentPane.setBorder(new LineBorder(new Color(0, 0, 0)));
setContentPane(contentPane);
contentPane.setLayout(null);
lblNewLabel = new JLabel("Welcome to MYHOTEL");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("Verdana", Font.PLAIN, 18));
lblNewLabel.setBounds(10, 11, 414, 23);
contentPane.add(lblNewLabel);
txtUsername = new JTextField();
txtUsername.setText("");
txtUsername.setBounds(222, 96, 94, 20);
contentPane.add(txtUsername);
txtUsername.setColumns(20);
lblNewLabel_1 = new JLabel("Username:");
lblNewLabel_1.setLabelFor(txtUsername);
lblNewLabel_1.setBounds(121, 99, 69, 14);
contentPane.add(lblNewLabel_1);
lblNewLabel_2 = new JLabel("Password:");
lblNewLabel_2.setBounds(121, 138, 69, 14);
contentPane.add(lblNewLabel_2);
btnLogin = new JButton("Login");
btnLogin.setBounds(169, 166, 89, 23);
contentPane.add(btnLogin);
btnSignUp = new JButton("Sign Up");
btnSignUp.setBounds(305, 215, 89, 23);
contentPane.add(btnSignUp);
btnForgotPassword = new JButton("Forgot password");
btnForgotPassword.setBounds(37, 215, 135, 23);
contentPane.add(btnForgotPassword);
pwdwhatever = new JPasswordField();
pwdwhatever.setText("");
pwdwhatever.setBounds(222, 136, 94, 17);
contentPane.add(pwdwhatever);
btnLogin.addActionListener(this);
btnSignUp.addActionListener(this);
btnForgotPassword.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent ae) {
// TODO Auto-generated method stub
Object o=ae.getSource();
if(o==btnLogin)
{
String uname,pass;
uname=txtUsername.getText();
pass=pwdwhatever.getText();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","hm","hm");
ps=con.prepareStatement("select * from account where username=? and password=?");
ps.setString(1,uname);
ps.setString(2,pass);
rs=ps.executeQuery();
if(rs.next())
{
System.out.println("Valid User.");
JOptionPane.showMessageDialog(this,"Valid User","Done",JOptionPane.INFORMATION_MESSAGE);
this.dispose();
rs.close();
ps.close();
//new homepage();
}
else
{
JOptionPane.showMessageDialog(this,"Incorrect","Error",JOptionPane.ERROR_MESSAGE);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
if(o==btnSignUp)
{
this.dispose();
new sign_up().setVisible(true);
}
if(o==btnForgotPassword)
{
this.dispose();
new forget().setVisible(true);
}
}
}
`
forget page
` package hM_prac;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPasswordField;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class forget extends JFrame implements ActionListener {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JPasswordField passwordField;
JButton btnSubmit,btnSubmitAnswer;
JLabel label,lblNewLabel_3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
System.out.println("hh");
forget window = new forget();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public forget() {
//super("login");
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 374, 358);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Username:");
lblNewLabel.setBackground(Color.BLACK);
lblNewLabel.setBounds(18, 77, 92, 14);
frame.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Security Question:");
lblNewLabel_1.setBackground(Color.BLACK);
lblNewLabel_1.setBounds(18, 139, 132, 14);
frame.getContentPane().add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel("Answer:");
lblNewLabel_2.setBackground(Color.BLACK);
lblNewLabel_2.setBounds(18, 164, 92, 14);
frame.getContentPane().add(lblNewLabel_2);
//frame.getContentPane().add(lblNewLabel_3);
JLabel lblNewLabel_5 = new JLabel("Forgot password");
lblNewLabel_5.setFont(new Font("Tahoma", Font.BOLD, 19));
lblNewLabel_5.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel_5.setBounds(10, 11, 338, 23);
frame.getContentPane().add(lblNewLabel_5);
textField = new JTextField();
textField.setBackground(Color.WHITE);
textField.setBounds(156, 77, 182, 14);
frame.getContentPane().add(textField);
textField.setColumns(10);
btnSubmit = new JButton("Submit ");
btnSubmit.setBackground(Color.WHITE);
btnSubmit.setBounds(184, 102, 142, 23);
frame.getContentPane().add(btnSubmit);
label = new JLabel("..");
label.setBackground(Color.BLACK);
label.setBounds(160, 139, 178, 14);
frame.getContentPane().add(label);
textField_1 = new JTextField();
textField_1.setBounds(156, 164, 192, 14);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
btnSubmitAnswer = new JButton("Submit Answer");
btnSubmitAnswer.setBackground(Color.WHITE);
btnSubmitAnswer.setBounds(184, 189, 142, 23);
frame.getContentPane().add(btnSubmitAnswer);
//frame.getContentPane().add(btnSubmitPassword);
btnSubmit.addActionListener(this);
btnSubmitAnswer.addActionListener(this);
}
Connection con;
PreparedStatement ps;
ResultSet rs;
private JButton btnSubmitPassword;
public void actionPerformed(ActionEvent ae) {
Object o=ae.getSource();
String uname;
if(o==btnSubmit)
{ System.out.println("ques");
uname=textField.getText();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","hm","hm");
ps=con.prepareStatement("select security_question from account where username=?");
ps.setString(1,uname);
rs=ps.executeQuery();
if(rs.next())
{
String secq=rs.getString("security_question");
System.out.println("question"+secq);
label.setText(secq);
frame.getContentPane().add(label);
}
else if(rs==null){
JOptionPane.showMessageDialog(this,"No such user","Error",JOptionPane.ERROR_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(this,"Invalid User","Error",JOptionPane.ERROR_MESSAGE);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
else if(o==btnSubmitAnswer)
{
//System.out.println("jj");
String ans;
uname=textField.getText();
ans=textField_1.getText();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","hm","hm");
ps=con.prepareStatement("select * from account where username=? and answer=?");
ps.setString(1,uname);
ps.setString(2,ans);
rs=ps.executeQuery();
if(rs!=null)
{
System.out.println("jj");
lblNewLabel_3 = new JLabel("New Password:");
lblNewLabel_3.setBackground(Color.BLACK);
lblNewLabel_3.setBounds(18, 226, 117, 14);
frame.getContentPane().add(lblNewLabel_3);
passwordField = new JPasswordField();
passwordField.setBackground(Color.BLACK);
passwordField.setBounds(160, 226, 178, 17);
//frame.getContentPane().add(passwordField);
frame.getContentPane().add(passwordField);
btnSubmitPassword = new JButton("Submit password");
btnSubmitPassword.setBounds(82, 285, 182, 23);
frame.getContentPane().add(btnSubmitPassword);
btnSubmitPassword.addActionListener(this);
}
else{
JOptionPane.showMessageDialog(this,"Wrong answer","Error",JOptionPane.ERROR_MESSAGE);
}
}catch(Exception e){
e.printStackTrace();
}
}
else if(o==btnSubmitPassword){
String pass;
uname=textField.getText();
pass=passwordField.getText();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","hm","hm");
ps=con.prepareStatement("update account set password=? where username=?");
ps.setString(1,pass);
ps.setString(1,uname);
rs=ps.executeQuery();
if(rs==null)
{
JOptionPane.showMessageDialog(this,"Error","Error",JOptionPane.ERROR_MESSAGE);
}
else{
JOptionPane.showMessageDialog(this,"Password reset","Error",JOptionPane.ERROR_MESSAGE);
this.dispose();
new login();
}}catch(Exception e){
e.printStackTrace();
}
}
}
}
`
Here is a better way to show another window from a JFrame (as is in this case of showing a "forgot password" window from "login" window) is to define it as a modal JDialog. Here is some working code to demonstrate what is possible:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainWindow {
public static void main(String [] args) {
new MainWindow();
}
private JFrame frame;
public MainWindow() {
frame = new JFrame("Main Window - login");
JButton button = new JButton("Click me to open dialog");
button.addActionListener(new ButtonListener());
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 300);
frame.setLocation(200, 200);
frame.setVisible(true);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
new DialogWindow();
}
}
}
class DialogWindow {
DialogWindow() {
JDialog dialog = new JDialog();
dialog.setTitle("Dialog - forgot");
dialog.setModal(true);
dialog.add(new JLabel("Do something here..."));
dialog.setSize(250, 150);
dialog.setLocation(600, 200);
dialog.setVisible(true);
}
}
In the above code the MainWindow can be assumed as the login window and the DialogWindow as the forgot password dialog. When the user clicks the button in the login window, the forgot dialog opens as a modal window. Then the user does some work in the forgot dialog; and on closing it returns to the main window.
Here is a link to Oracle's Java Swing tutorials with examples of how to use JFrame, JDialog and other GUI components.
I am developing a basic program that has 3 JFrames. A log-in, a registration and a Dashboard to be opened after successful log-in attempt. However, I am getting an error after typing in the username and password and clicking log-in button.
Here's the error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' password='1234'' at line 1
And here's my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.mysql.jdbc.Statement;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.ImageIcon;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.awt.event.ActionEvent;
public class Login extends JFrame {
private JPanel contentPane;
private JTextField txtUsrName;
private JTextField txtPAss;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login frame = new Login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Login() {
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 450, 348);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblLogin = new JLabel("Welcome To TechApp");
lblLogin.setFont(new Font("Tekton Pro", Font.PLAIN, 18));
lblLogin.setBounds(135, 19, 163, 28);
contentPane.add(lblLogin);
JLabel lblUsername = new JLabel("UserName:");
lblUsername.setFont(new Font("Alaska", Font.PLAIN, 15));
lblUsername.setBounds(174, 58, 88, 28);
contentPane.add(lblUsername);
txtUsrName = new JTextField();
txtUsrName.setBounds(145, 90, 132, 20);
contentPane.add(txtUsrName);
txtUsrName.setColumns(10);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setFont(new Font("Alaska", Font.PLAIN, 15));
lblPassword.setBounds(182, 118, 95, 46);
contentPane.add(lblPassword);
txtPAss = new JTextField();
txtPAss.setColumns(10);
txtPAss.setBounds(145, 156, 132, 20);
contentPane.add(txtPAss);
JButton btnNewButton = new JButton("login");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String _username = txtUsrName.getText();
String _password = txtPAss.getText();
String url = "jdbc:mysql://127.0.0.1:3306/javabase";
String user = "java";
String passw = "password";
try{
// 1.Get a connection To Database
Connection myConn = DriverManager.getConnection(url, user, passw);
// 2.Create a statement
Statement myStmt = (Statement) myConn.createStatement();
// 3.Execute SQL Query
String sql = "SELECT userame, password FROM registration WHERE userame='"+_username+"', password='"+_password+"' ";
ResultSet result = myStmt.executeQuery(sql);
//myStmt.executeUpdate(sql);
int count = 0;
while(result.next()){
count = count + 1;
}
if(count == 1){
Dashboard frame = new Dashboard();
frame.setVisible(true);
}
else if(count > 1){
JOptionPane.showMessageDialog(null, "Duplicate User! Access Denied!");
}
else{
JOptionPane.showMessageDialog(null, "User Not Found!");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
btnNewButton.setBounds(169, 202, 89, 49);
contentPane.add(btnNewButton);
JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main frame = new Main();
frame.setVisible(true);
}
});
btnRegister.setBounds(168, 264, 89, 23);
contentPane.add(btnRegister);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setFont(new Font("Alaska", Font.PLAIN, 16));
lblNewLabel.setIcon(new ImageIcon("D:\\ExploitGate\\MAS-9831-Offwhite2.jpg"));
lblNewLabel.setBounds(0, 0, 434, 310);
contentPane.add(lblNewLabel);
}
}
I've searched the stackoverflow forum and carried out the possible solution given here
Can anyone please guide me how to handle this error?
Thanks In Advance :)
All of the above code is basically useless. It's an SQL syntax error, which means it's this one line:
... WHERE userame='"+_username+"', password='"+_password+"' ";
^---
you don't use , to separate where clause arguments. You use boolean operations. and, or, etc...
And note that you're vulnerable to sql injection attacks
You were using a comma , between your WHERE clauses rather than an AND.
String sql = "SELECT userame, password FROM registration WHERE userame='"+_username+"' AND password='"+_password+"' ";
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.
I have a query. I have a database, and I am trying to write code, so that a record in the database can be created from the java software.
I have a connector class that connects to the database, then a registerStudent class, that lets the user type in value into 2 textfields. then the values should be used to create a record in the database table.
when i hit the submit button it gives me this error code:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at RegisterStudent$2.actionPerformed(RegisterStudent.java:99)
FYI - Line 99 Code =
con.stmt.executeUpdate("INSERT INTO staff (Name, Profession)"+"VALUES"+"("+"'"+name+"',"+"'"+profession+"')");
This is my code for the registerStudent class:
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
public class RegisterStudent
{
public RegisterStudent() {
initialize();
}
public JFrame frmRegisterStudent;
Connector con;
private JTextField textField_1;
private JTextField textField_2;
// initialise the frame
private void initialize() {
frmRegisterStudent = new JFrame();
frmRegisterStudent.setTitle("LEC AdminPro: RegisterStudents");
frmRegisterStudent.setBounds(100, 100, 413, 225);
frmRegisterStudent.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frmRegisterStudent.setLocationRelativeTo(null);
Border border = LineBorder.createGrayLineBorder();
frmRegisterStudent.getContentPane().setLayout(null);
con = new Connector();
JPanel panel_1 = new JPanel();
panel_1.setBounds(0, 0, 397, 189);
frmRegisterStudent.getContentPane().add(panel_1);
panel_1.setBorder(border);
panel_1.setLayout(null);
JLabel lblRegister = new JLabel("Register Student");
lblRegister.setFont(new Font("Tahoma", Font.BOLD, 12));
lblRegister.setBounds(10, 11, 124, 20);
panel_1.add(lblRegister);
JLabel lblSurname = new JLabel("Name");
lblSurname.setFont(new Font("Arial", Font.PLAIN, 11));
lblSurname.setBounds(10, 63, 69, 14);
panel_1.add(lblSurname);
JLabel lblDob = new JLabel("Profession");
lblDob.setFont(new Font("Arial", Font.PLAIN, 11));
lblDob.setBounds(10, 88, 69, 14);
panel_1.add(lblDob);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(104, 63, 266, 20);
panel_1.add(textField_1);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(104, 88, 266, 20);
panel_1.add(textField_2);
JButton btnNewButton = new JButton("Cancel");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Object[] options = {"Yes", "No"};
Component form = null;
int n = JOptionPane.showOptionDialog(form, "Would you like to cancel the new Registration?", "Exit Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options);
if(n == JOptionPane.YES_OPTION) {
frmRegisterStudent.setVisible(false);
}
}
});
btnNewButton.setBounds(280, 119, 89, 23);
panel_1.add(btnNewButton);
JButton button = new JButton("Submit");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String name = textField_1.getText();
String profession = textField_1.getText();
try {
con.stmt.executeUpdate("INSERT INTO staff (Name, Profession)"+"VALUES"+"("+"'"+name+"',"+"'"+profession+"')");
JOptionPane.showMessageDialog(frmRegisterStudent, "New Record has been added");
} catch (SQLException e) {
System.out.println("Record couldn't be added!");
e.printStackTrace();
}
}
});
button.setBounds(181, 119, 89, 23);
panel_1.add(button);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RegisterStudent window = new RegisterStudent();
window.frmRegisterStudent.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
public void setVisible(boolean b) {
frmRegisterStudent.setVisible(true);
}
}
It looks like the problem is in the Connector class, which has a stmt field that does not get initialized.
Use this instead of the line with the NullPointerException
con.stmt = con.conn.prepareStatement("insert into staff (name, profession) values (?, ?)");
con.stmt.setString(1, name);
con.stmt.setString(2, profession);
con.stmt.executeUpdate();
But note that this is pretty bad design.
Is your connector null? I see the stmt is a field in the connector, have you initialized it?
By the way using a prepared statement is much better in your case, because it will escape the Strings (for example if they have "'" in them).
PreparedStatement pstmt = connection.prepareStatement("insert into staff (name, profession) values (?, ?)");
pstmt.setString(1, name);
pstmt.setString(2, profession);
pstmt.executeUpdate();