Hi everybody,
I want to have a login form in Java, which comparing the username and password, according to MySQL database data, so I have the following code, just don't know where to add the select statement and how verify the username and password from MySQL with the JTextfield of the JAVA:
code...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import javax.swing.JOptionPane;
public class Login extends JFrame implements ActionListener {
private Container container;
private GridBagLayout layout;
private GridBagConstraints gbc;
private JButton cmdLogin, cmdCancel;
private JLabel lblUSer, lblPassword;
private JTextField txtUser;
private JPasswordField txtPassword;
public Login()
{
setTitle("Login Screen"); // or //super("Login window");
setExtendedState(JFrame.MAXIMIZED_BOTH);
setResizable(false); //disable resizing and Max button
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(300,150);
setLocationRelativeTo(null);
container = getContentPane();
layout = new GridBagLayout();
container.setLayout(layout);
gbc = new GridBagConstraints();
lblUSer = new JLabel("Username:");
gbc.insets = new Insets(2,2,2,2);
container.add(lblUSer, gbc);
txtUser = new JTextField(15);
gbc.gridx = 1;
gbc.gridwidth = 3;
container.add(txtUser, gbc);
lblPassword = new JLabel("Password:");
gbc.gridy = 1;
gbc.gridx = 0;
gbc.gridwidth = 1;
container.add(lblPassword, gbc);
txtPassword = new JPasswordField(15);
gbc.gridx = 1;
gbc.gridwidth = 3;
container.add(txtPassword, gbc);
cmdLogin = new JButton("Login");
cmdLogin.addActionListener( this );
gbc.gridy = 2;
gbc.gridx = 1;
gbc.gridwidth = 1;
container.add(cmdLogin, gbc);
cmdCancel = new JButton("Cancel");
cmdCancel.addActionListener( this );
gbc.gridx = 2;
container.add(cmdCancel, gbc);
} //Login()
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("Login")){
JOptionPane.showMessageDialog(null, "Wrong Username or Password, try again", "Warning !!!", JOptionPane.WARNING_MESSAGE);
}
else
{
//default icon, custom title
int respond = JOptionPane.showConfirmDialog(null, "Would you like exiting the program ?", "Exiting", JOptionPane.YES_NO_OPTION);
//System.out.println(respond);
if(respond == 0){
dispose (); //closing the frame
}
}
} //actionPerformed()
public static void connect()
{
Connection conn = null;
try
{
String userName = "root";
String password = "root";
String url = "jdbc:mysql://localhost/Member";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e)
{
/* ignore close errors */
}
}
}
} //connect()
public static void main(String args[]) {
new Login().setVisible(true);
connect();
} //main()
} //Login