Linking to another application when using preparestatement - java

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.

Related

I want to present the username from database JAVA Jframe

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

Not able to call Jframe from a contentpane

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.

SQL Syntax Error In Java and MySql SELECT Query

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+"' ";

String User & password combination isn't getting checked simple java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I am just a beginner in Java. Here, I want to make a User ID & Password input, which will get checked & tell its Right or wrong. But each time it's giving the wrong answer despite inputting the correct combination.
Here is my code:
import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Zihan {
public JFrame frame;
public JTextField textField;
public JPasswordField passwordField;
public static String gtxt,ptxt;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Zihan window = new Zihan();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Zihan() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblEmailuserId = new JLabel("Email/User ID:");
lblEmailuserId.setBounds(76, 30, 90, 14);
frame.getContentPane().add(lblEmailuserId);
textField = new JTextField();
textField.setBounds(171, 27, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(171, 87, 86, 20);
frame.getContentPane().add(passwordField);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(76, 90, 69, 14);
frame.getContentPane().add(lblPassword);
JButton btnLogIn = new JButton("Log In");
btnLogIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
gtxt = textField.getText();
ptxt = passwordField.getText();
new CheckID(gtxt,ptxt);
JFrame login = new JFrame("Login window");
login.setSize(200, 200);
login.setVisible(true);
JLabel msg = new JLabel();
msg.setText(CheckID.msgt);
login.getContentPane().add(msg);
frame.setVisible(false);
}
});
btnLogIn.setBounds(121, 137, 89, 23);
frame.getContentPane().add(btnLogIn);
}
}
& This is the CheckID class to check Email & Password:
public class CheckID {
public static String msgt;
String cU = "zihan";
String cP = "123";
CheckID(String tx ,String px){
if(tx==cU && px ==cP)
{
msgt = "Welcome to messenger";
}
else
{
msgt = "Sorry! Wrong Password/Email";
}
}
}
Change
if(tx==cU && px ==cP)
to
if(tx.equals(cU) && px.equals(cP))

Separate GUI class and main class

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.

Categories

Resources