In gui user enter username and password then click ok button.But the problem is i don't know how to connect with my Connector Class with ok button. And Give restriction to that button when user enter correct fields then connect to database.
Main Method
public class Main {
public static void main(String[] args) {
Gui obj = new Gui();
Connector conn = new Connector(obj.Setproperty());
}
}
Gui Class
public class Gui extends JFrame implements ActionListener{
private JLabel label1;
private JLabel label2;
private JTextField t1;
private JTextField t2;
private JButton ok;
private JPanel p1,p2;
Properties property;
public Gui(){
super("GUI");
p1 = new JPanel();
p1.setLayout(new GridLayout(0,2));
p2=new JPanel();
label1 = new JLabel("User Name");
t1 = new JTextField();
label2 = new JLabel("Password");
t2 = new JTextField();
ok= new JButton("OK");
ok.addActionListener(this);
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.SOUTH);
p1.add(label1);
p1.add(t1);
p1.add(label2);
p1.add(t2);
p2.add(ok);
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
property = new Properties();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==ok){
}
}
public Properties Setproperty(){
property.setProperty("UNAME",t1.getText());
property.setProperty("PWD",t2.getText());
return property;
}
}
Connector Class
public class Connector {
Connection conn;
Statement state;
String username;
String pass;
String url;
public Connector(Properties p) {
username = p.getProperty("UNAME");
pass = p.getProperty("PWD");
url= "jdbc:mysql://localhost/world";
}
public boolean open() {
try {
conn = DriverManager.getConnection(url, username, pass);
state = conn.createStatement();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
e.printStackTrace();
}
if(conn==null){
System.out.println("Connection is NULL or server not connected");
return false;
}
System.out.println("Connection Successfull");
return true;
}
}
Try changing the actionPerformed method to this:
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==ok){
Properties prop = Setproperty();
Connector c = new Connector(prop);
c.open();
}
}
Related
Im trying to create a banking system and to not make it boring we tried to add some image icon into the program in jlabel, when i tried to run the code and first pin mistake, removes the tester label successfully but the problem is when tries are equal to 4, Label pinwrongtester doesn't seem to remove instead it is mixing with the Label that i programmed when they entered pin 4 times, i hope you guys can help me to solve this mistakes
public void Option()
{
//option title
JLabel label = new JLabel("Choose Options");
label.setFont(new Font("Consolas",Font.BOLD,20));
JButton choose = new JButton();
choose.add(label);
choose.setBounds(200,300,200,40);
choose.setBackground(Color.white);
choose.setEnabled(false);
// Buttons Option
JButton Balance = new JButton("Balance");
JButton Withdraw= new JButton("Withdraw");
JButton Send = new JButton("Transfer");
JButton Exit = new JButton("Exit");
//Set Bounds
Balance.setBounds(50,350,200,40);
Withdraw.setBounds(50,450,200,40);
Send.setBounds(350,350,200,40);
Exit.setBounds(350,450,200,40);
//addActionListener
Balance.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pinbalance();
}
});
Withdraw.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pinwithdraw();
}
});
Send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pintransferfunds();
}
});
//add buttons and labels
p.add(choose);
p.add(Balance);
p.add(Withdraw);
p.add(Send);
p.add(Exit);
}
JPanel enterpinbg;
JFrame enterpinframe;
String account_name;
String balance;
String pindb;
JLabel tester;
JLabel pinwrongtester;
JLabel pinwrongertester;
JLabel balancetester;
JFrame balanceframe;
JPanel balancepanel;
ImageIcon enteryourpin;
ImageIcon pinwrong;
ImageIcon pinwronger;
ImageIcon balanceicon;
private LinkedList<String> picturetrans;
JTextField inputpin;
boolean police = false;
int x =0;
public void pinbalance()
{
//PIN FRAME
enterpinframe = new JFrame("Enter Pin");
enterpinframe.setSize(WIDTH,HEIGHT);
enterpinframe.setVisible(true);
enterpinframe.setResizable(false);
enterpinframe.setLocationRelativeTo(null);
enterpinframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//PIN PANEL
enterpinbg = new JPanel();
enterpinbg.setSize(WIDTH,HEIGHT);
enterpinbg.setBackground(Color.orange);
enterpinbg.setVisible(true);
enterpinbg.setLayout(null);
enterpinframe.add(enterpinbg);
inputpin = new JTextField();
inputpin.setFont(new Font("Consolas",Font.BOLD,20));
inputpin.setForeground(Color.gray);
//Setbounds
inputpin.setBounds(250,600,100,40);
//tester + image
enteryourpin = new ImageIcon(getClass().getResource("Enter yout PIN.png"));
tester = new JLabel(enteryourpin);
tester.setBounds(50,50,500,500);
//enterpin Add
enterpinbg.add(tester);
enterpinbg.add(inputpin);
this.dispose();
inputpin.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==(KeyEvent.VK_ENTER))
{
String pinx = inputpin.getText();
Connection con= null;
Statement stmt = null;
try
{
Class.forName(JDBC_DRIVER1);
Class.forName(JDBC_DRIVER2);
con = DriverManager.getConnection(URL,USER,PASS);
stmt=con.createStatement();
String sql ="SELECT*FROM TBL_BANK WHERE PIN ='"+pinx+"' ";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
{
pindb = rs.getString("PIN");
account_name = rs.getString("ACCOUNT_NAME");
balance = rs.getString("BALANCE");
}
rs.close();
}
catch(Exception f)
{
System.out.println(f);
}
//if Login Success and Failed
if(pinx.equals(pindb))
{
// Balance will show up
}
else if(pinx!=(pindb))
{
enterpinbg.remove(tester);
x++;
System.out.println("x");
inputpin.setText("");
pinwrong = new ImageIcon(getClass().getResource("PIN Wrong (1_2Times).png"));
pinwrongtester = new JLabel(pinwrong);
pinwrongtester.setBounds(50,50,500,500);
enterpinbg.add(pinwrongtester);
enterpinbg.repaint();
if(x>=4 )
{
// this doesnt quite work please help me fix it
enterpinbg.remove(pinwrongtester);
enterpinbg.repaint();
}
}
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
i am making java app for my minor project.i am entering correct data but it not allowing to login.i am confused why the code in not working.
there are 2 fields in my database(username and pass ).i am entering correct data but it allowing me to login
`
public class login extends JFrame implements ActionListener{
JButton jb1;
JTextField tf3,tf1,tf2;
ResultSet rs;
String s2,s1,s3;
String a;
Connection con;
login(){
Container c =getContentPane();
c.setLayout(null);
c.setBackground(Color.orange);
jb1=new JButton("submit");
jb1.addActionListener(this);
jb1.setBounds(180,370,100,50);
JLabel jl1=new JLabel("username");
jl1.setBounds(10,60,100,50);
JLabel jl2=new JLabel("password");
jl2.setBounds(10,110,100,50);
JLabel jl3=new JLabel("user or emp");
jl3.setBounds(10,160,100,50);
tf1= new JTextField();
tf1.setBounds(110,70,200,40);
tf2= new JTextField();
tf2.setBounds(110,120,200,40);
tf3=new JTextField();tf3.setBounds(110,180,200,40);
tf1.setText("username");
tf2.setText("password");
c.add(tf1);c.add(tf2);c.add(tf3);
c.add(jl1);c.add(jl2);c.add(jl3);
c.add(jb1);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==jb1){
s1 = tf1.getText();
s2 = tf2.getText();
s3 = tf3.getText();
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "scott", "hr");
PreparedStatement ps = con.prepareStatement("select * from login ");
rs = ps.executeQuery();
while(rs.next()) {
String username = rs.getString("username");
String pass = rs.getString("pass");
if ((s1.equals(username)) && (s2.equals(pass))) {
if (s3.equals("Admin")) {
dispose();
home f=new home();
f.setSize(500,500);
f.setTitle("Bank Management System");
f.setVisible(true);
} else if (s3.equals("user")) {
dispose();
} else {
dispose();
}
} else {
JOptionPane.showMessageDialog(null, "User name and password do" + " not match!","ALERT!",JOptionPane.ERROR_MESSAGE);
break;
}
}
}
catch(Exception ex)
{
System.out.println( ex);
}
}
}
public static void main(String[] args) {
login af =new login();
af.setSize(500,500);
af.setTitle("login");
af.setVisible(true);
}
}
`
I want to enter data through textfields and save them. But buttons are not working. There are no errors while I'm compiling and not even in database connection. I guess there is a logical error.
public class Database {
private static JPanel panel;
private static JLabel sname;
private static JLabel saddress;
private static JTextField t;
private static JTextField t1;
private static JButton Delete = new JButton("Delete");
private static JButton update = new JButton("Update");
private static JButton save = new JButton("Save");
private static Container c;
private static Connection con;
private static Statement st;
private static ResultSet rs;
Database() {
connect();
}
public void connect(){
try{
System.out.println("Entered");
System.out.println("Database connection started...");
con=DriverManager.getConnection("jdbc:ucanaccess://D:\\test.mdb");
System.out.println("Hello satarted");
st = con.createStatement();
System.out.println("Connection ok.");
while(rs.next())
{
System.out.println(rs.getString("Student Name"));
System.out.println(rs.getString("Student Address"));
System.out.println();
}
catch (SQLException e){
System.err.println("Exception: " + e.getMessage());
}
}
public static void main(String[] args) {
Database gui = new Database();
JFrame f = new JFrame();
f.setTitle("School Management System");
f.setSize(300, 200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sname = new JLabel("Student Name");
t = new JTextField(10);
saddress = new JLabel("Student Address");
t1 = new JTextField(10);
panel = new JPanel();
panel.add(sname);
panel.add(t);
panel.add(saddress);
panel.add(t1);
// panel.add(insert);
panel.add(Delete);
panel.add(update);
panel.add(save);
f.add(panel);
try {
rs.next();
t.setText(rs.getString("Student Name"));
t1.setText(rs.getString("Student Address"));
} catch (Exception ex) {
}
}
public void btnAction() {
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = t.getText();
String address = t1.getText();
try {
rs.moveToInsertRow();
rs.updateString("Student Name", name);
rs.updateString("Student Address", address);
rs.insertRow();
rs.close();
} catch (Exception ex) {
}
}
});
update.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String sname = t.getText();
String saddress = t1.getText();
try {
rs.updateString("Student name", sname);
rs.updateString("Student address", saddress);
rs.updateRow();
JOptionPane.showMessageDialog(null, "Record Updated!");
} catch (Exception e) {
}
}
});
}
}
when i removed static from each of these variables. I got so many errors
Yes, any time you see a class full of static variables you know the class is designed incorrectly.
Start with the working example from the Swing tutorial on How to Use Text Field. Download the TextDemo code and understand how it works and then make the changes for your logic.
Note how the class extends a JPanel where all the variables and components are defined and there is no need for any static variable. Your code should look something like this.
Once you have a better designed class you can then start to debug your code to figure out why the SQL isn't working.
I'm facing a problem in this program there are two GUI's.When user click on button it checks for a database connection when connection become successful then second GUI appear which has JComboBox. But the problem is it doesn't show the catalogs of mysql in JComboBox.
Main Method:
public class Main {
public static void main(String[] args) {
Gui obj = new Gui();
}
}
First Gui
public class Gui extends JFrame {
Connector c = new Connector();
private JButton b1;
public Gui() {
b1 = new JButton("Click To Connect");
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (c.getConnect() == true) {
dispose();
new Gui2();
}
}
});
add(b1);
setLayout(new FlowLayout());
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Connection Class
public class Connector {
private Connection conn;
public boolean getConnect() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/", "john", "root");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
if (conn == null) {
System.out.println("Connection Failed");
return false;
}
System.out.println("Connection Success");
return true;
}
}
ComboBox GUI
public class Gui2 extends JFrame {
private JComboBox box;
Connection connection;
public Gui2() {
box = new JComboBox();
opencatalog();
add(box);
setLayout(new FlowLayout());
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
private void opencatalog() {
try {
DatabaseMetaData meta = connection.getMetaData();
ResultSet rs = meta.getCatalogs();
List ct = new ArrayList();
while (rs.next()) {
ct.add(rs.getString(1));
}
rs.close();
box.setModel(new DefaultComboBoxModel(ct.toArray()));
box.setSelectedItem(connection.getCatalog());
box.setEnabled(ct.size() > 0);
}
catch (Exception e) {
System.out.println(e.toString());
}
box.setEnabled(false);
}
}
Connector class
change the return type to Connection and return conn.
public Connection getConnect() {
....
return conn
}
Gui class, change the condition
public void actionPerformed(ActionEvent arg0) {
Connection conn= c.getConnect();
if (conn!=null) {
new Gui2(conn);//pass connection object here
dispose();
}
}
Gui2 class, constructor should be
public Gui2(Connection conn)
{
connection=conn;
box = new JComboBox();
.................
}
Gui2 class,
box.setEnabled(true);//should be enabled,
Trying to set up a JDBC that checks a database for a matching username and password, and they when the login button is pressed if matching the user is granted access, I've got my current code here, but I'm unsure what is missing when I launch the program it seems like its not checking the database for the correct information.
Updated:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class NewClass extends JFrame {
private JTextField jtfUsername, jtfPassword;
private JButton backButton, loginButton;
private JMenuItem jmiLogin, jmiBack, jmiHelp, jmiAbout;
NewClass() {
//create menu bar
JMenuBar jmb = new JMenuBar();
//set menu bar to the applet
setJMenuBar(jmb);
//add menu "operation" to menu bar
JMenu optionsMenu = new JMenu("Options");
optionsMenu.setMnemonic('O');
jmb.add(optionsMenu);
//add menu "help"
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
helpMenu.add(jmiAbout = new JMenuItem("About", 'A'));
jmb.add(helpMenu);
//add menu items with mnemonics to menu "options"
optionsMenu.add(jmiLogin = new JMenuItem("Login", 'L'));
optionsMenu.addSeparator();
optionsMenu.add(jmiBack = new JMenuItem("Back", 'B'));
//panel p1 to holds text fields
JPanel p1 = new JPanel(new GridLayout(2, 2));
p1.add(new JLabel("Username"));
p1.add(jtfUsername = new JTextField(15));
p1.add(new JLabel("Password"));
p1.add(jtfPassword = new JPasswordField(15));
//panel p2 to holds buttons
JPanel p2 = new JPanel(new FlowLayout());
p2.add(backButton = new JButton("Back"));
p2.add(loginButton = new JButton("Login"));
//Panel with image??????
//add panels to frame
JPanel panel = new JPanel(new GridLayout(2, 1));
panel.add(p1, BorderLayout.CENTER);
panel.add(p2, BorderLayout.SOUTH);
add(panel, BorderLayout.CENTER);
setTitle("Main Page");
//listners for exit menuitem and button
jmiBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Welcome welcome = new Welcome();
welcome.setVisible(true);
welcome.setSize(500, 500);
welcome.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Welcome welcome = new Welcome();
welcome.setVisible(true);
welcome.setSize(500, 500);
welcome.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
//listner for about menuitem
jmiAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"This is the login panel"
+ "\n Assignment for University",
"About", JOptionPane.INFORMATION_MESSAGE);
}
});
//action listeners for Login in button and menu item
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
usernamecheck.checkLogin(jtfUsername.getText(), jtfPassword.getText()); {
System.out.println("User is validated");
}
} catch (SQLException se) {
}
MainMenu mainmenu = new MainMenu();
mainmenu.setVisible(true);
mainmenu.setSize(500, 500);
mainmenu.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
jmiLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainMenu mainmenu = new MainMenu();
mainmenu.setVisible(true);
mainmenu.setSize(500, 500);
mainmenu.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
}
public static void main(String arg[]) {
log frame = new log();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class usernamecheck {
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/test";
static final String USERNAME = "root";
static final String PASSWORD = "root";
// launch the application
public static boolean checkLogin(String username, String password)
throws SQLException {
System.out.print("dfdF");
Connection connection = null; // manages connection
PreparedStatement pt = null; // manages prepared statement
// connect to database usernames and query database
try {
// establish connection to database
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DATABASE_URL, "root", "root");
// query database
pt = con.prepareStatement("select userName,password from test.person where userName=?");
// process query results
pt.setString(1, username);
ResultSet rs = pt.executeQuery();
String orgUname = "", orPass = "";
while (rs.next()) {
orgUname = rs.getString("userName");
orPass = rs.getString("password");
} //end while
if (orPass.equals(password)) {
//do something
return true;
} else {
//do something
}
}//end try
catch (Exception e) {
} //end catch
return false;
} //end main
}
Make your checkLogin method return boolean type and return true inside if (orPass.equals(password)) { block. Check whether the method true if so grant access.
You are missing a return type in your checkLogin method. You may return a boolean value to validate the user. Also add some logging/sysout to make sure what is happening in your code.
Update your method as :
// launch the application
public static boolean checkLogin(String username, String password)
throws SQLException {
System.out.print("dfdF");
Connection connection = null; // manages connection
PreparedStatement pt = null; // manages prepared statement
// connect to database usernames and query database
try {
// establish connection to database
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DATABASE_URL, "root", "root");
// query database
pt = con.prepareStatement("select userName,password from test.person where userName=?");
// process query results
pt.setString(1, username);
ResultSet rs = pt.executeQuery();
String orgUname = "", orPass = "";
while (rs.next()) {
orgUname = rs.getString("userName");
orPass = rs.getString("password");
} //end while
if (orPass.equals(password)) {
//do something
return true;
rs.close();
} else {
//do something
}
}//end try
catch (Exception e) {
} //end catch
return false;
} //end main
And then update your user check as
try {
if(usernamecheck.checkLogin(jtfUsername.getText(), jtfPassword.getText())) {
System.out.println("User is validated");
} else {
return;
}
} catch (SQLException se) {
}