Am trying to create login page for my application and i did it well but i couldn't able to add a image to my JFrame, here is my code for login page....
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.*;
public class log extends JFrame {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://sqldatabase.com/databasename";
// Database credentials
static final String USER = "usernamr";
static final String PASS = "pass";
public static void main(String[] args) throws IOException {
log frameTabel = new log();
}
JButton blogin = new JButton("Login");
JPanel panel = new JPanel();
JLabel label = new JLabel();
JTextField txuser = new JTextField(15);
JPasswordField pass = new JPasswordField(15);
log() throws IOException{
super("Login Autentification");
setSize(500,500);
setLocation(300,280);
panel.setLayout (null);
//ImageIcon image = new ImageIcon("image.jpeg");
//JLabel hangman = new JLabel(new ImageIcon(urlOfImageFile));
//panel.add(image, BorderLayout.NORTH);
//Image image = ImageIO.read(new File("F:\\IModubytes\\Images\\1.jpg"));
//JLabel picLabel = new JLabel(new ImageIcon(image));
//panel.add(picLabel);
//panel.repaint();
txuser.setBounds(300,100,150,20);
pass.setBounds(300,135,150,20);
blogin.setBounds(380,170,80,20);
panel.add(blogin);
panel.add(txuser);
panel.add(pass);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
actionlogin();
}
public void actionlogin(){
blogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String puname = txuser.getText();
String ppaswd = pass.getText();
String sql = "SELECT * FROM EmpDetails WHERE id="+puname;
System.out.println(puname);
ResultSet rs = stmt.executeQuery(sql);
String pw = null;
while(rs.next()) {
pw = rs.getString("pass");
}
rs.close();
//if(puname.equals("test") && ppaswd.equals(pw)) {
if(ppaswd.equals(pw)) {
newFrame regFace =new newFrame();
regFace.setVisible(true);
dispose();
} else {
JOptionPane.showMessageDialog(null,"Wrong Password / Username");
txuser.setText("");
pass.setText("");
txuser.requestFocus();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Can anyone please help me how to add image in this....
You already have the code to load the image and add the label to your frame.
So the next step is to add your components to the label and then add the label to the content pane, instead of adding the components to the panel and adding the panel to the content pane.
Also, don't use a null layout!!! Swing was designed to be used with layout mangers. Read the section from the Swing tutorial on Layout Managers for more information and working examples.
Related
Evening all,
So I've been working on creating a local database using SQLite. (As a plugin that is part of Firefox). It uses three classes:
databaseConnection
Login
Display
and two tables (which come under the database MyFilms) called:
Users
MyFilms
databaseConnection is used to simply just connect to my SQLite database MyFilms, which it does fine.
The second class, Login, access my Users table from my database so it can access the logins and proceed to my GUI called Display.
Display will load the following GUI, which consists of a button, which when clicked is supposed to load the data from my database table MyFilms into a JTable:
However, when I click the button, nothing loads... it even looks like the JTable is not there, but when I check my code it defiantly is!
The code where I think the problem might lie is:
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query ="Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception anException){
anException.printStackTrace();
}
}
});
Any idea why the database is not showing here? Please find the code to each class below:
databaseConnection:
import java.sql.*;
import javax.swing.*;
public class databaseConnection {
Connection conn = null;
public static Connection dbConnector(){
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Joe\\workspace\\MyFilms.sqlite");
JOptionPane.showMessageDialog(null, "Connection Successful!");
return conn;
}
catch(Exception anException)
{
JOptionPane.showMessageDialog(null, anException);
return null;
}
}
}
Login:
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.sql.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login {
private JFrame frmTest;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frmTest.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
private JTextField textFieldUN;
private JPasswordField passwordField;
/**
* Create the application.
*/
public Login() {
initialize();
connection = databaseConnection.dbConnector();
}
/**
* Initialise the contents of the frame.
*/
private void initialize() {
frmTest = new JFrame();
frmTest.setTitle("Database Login");
frmTest.setBounds(100, 100, 345, 184);
frmTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTest.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Username:");
lblNewLabel.setBounds(34, 37, 64, 14);
frmTest.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Password:");
lblNewLabel_1.setBounds(34, 66, 64, 14);
frmTest.getContentPane().add(lblNewLabel_1);
textFieldUN = new JTextField();
textFieldUN.setBounds(126, 34, 151, 20);
frmTest.getContentPane().add(textFieldUN);
textFieldUN.setColumns(10);
JButton btnLogin = new JButton("Login");
frmTest.getRootPane().setDefaultButton(btnLogin);
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query = "Select * from Users where username=? and password=?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, textFieldUN.getText());
pst.setString(2, passwordField.getText());
ResultSet rs = pst.executeQuery();
int count = 0;
while(rs.next()){
count = count +1;
}
if (count == 1){
frmTest.dispose();
Display GUI = new Display();
GUI.setVisible(true);
}
else if (count > 1){
JOptionPane.showMessageDialog(null, "Duplicate Username and Password");
}
else{
JOptionPane.showMessageDialog(null, "Username or Password is not correct - Please try again..");
}
rs.close();
pst.close();
}
catch (Exception anException){
JOptionPane.showMessageDialog(null, anException);
}
}
});
btnLogin.setBounds(126, 111, 89, 23);
frmTest.getContentPane().add(btnLogin);
passwordField = new JPasswordField();
passwordField.setBounds(126, 64, 151, 17);
frmTest.getContentPane().add(passwordField);
}
}
Display:
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.JButton;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class Display extends JFrame {
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Display frame = new Display();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Display() {
connection = databaseConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 711, 443);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query ="Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception anException){
anException.printStackTrace();
}
}
});
btnLoadData.setBounds(596, 11, 89, 23);
contentPane.add(btnLoadData);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(684, 45, -675, 349);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
}
}
Any help would be greatly appreciated! Cheers..
However, when I run it in Eclipse I receive no errors at all. It runs fine, just does not display the database in the JTable.
Could you please replace your Display.java with the following:
Display.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
public class Display extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Display frame = new Display();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Display() {
connection = databaseConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 711, 443);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout());
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception anException) {
anException.printStackTrace();
}
}
});
// btnLoadData.setBounds(596, 11, 89, 23);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BorderLayout());
buttonPanel.add(btnLoadData, BorderLayout.EAST);
contentPane.add(buttonPanel, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane();
// scrollPane.setBounds(684, 45, -675, 349);
table = new JTable();
scrollPane.setViewportView(table);
contentPane.add(scrollPane, BorderLayout.CENTER);
}
}
and see the results?
Few changes have been made to your code. They are:
1) You first added scrollPane to the contentPane then you added table to scrollPane. I changed the order.
2) You used absolute layout. I changed that with BorderLayout.
The result displayed on my system is:
Hope this helps!
I created a login applet that that I want to open another main applet once the user logins but I cant seems to get it to work right. I tried making an object of themain applet and then invoking it but that didnt work so then I tried creating another pane for the new applet and setting it inside of the login applet but that didnt work. Can someone tell me what im doing wrong?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.applet.Applet;
public class login extends Applet implements ActionListener{
FundRaiserApplet secondApplet;
JLabel uname = new JLabel("Username");
JLabel pname = new JLabel("Password");
JTextField username = new JTextField(15);
JPasswordField password = new JPasswordField(15);
JButton login = new JButton("Login");
static final String USER = "identityone";
static final String PASS = "test";
JLabel status = new JLabel("");
JPanel fundraiserPanel;
public void init(){
setSize(250,200);
add(uname);
add(username);
add(pname);
add(password);
add(login);
add(status);
login.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == login){
//status.setText("Password or Username is incorrect");
String user = username.getText();
String pass = password.getText();
try{
Class.forName("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/Credentials;user=test;password=test");
Statement stmt = conn.createStatement();
Statement credR = conn.createStatement();
String credentialSet = "INSERT INTO Credentials" +"( username, password)" + " VALUES('" + USER +"' , '" + PASS +"' )";
stmt.executeUpdate(credentialSet);
ResultSet ret = credR.executeQuery("SELECT username , password FROM Credentials");
while (ret.next()) {
if(user.equals(ret.getString("username")) && pass.equals(ret.getString("password"))) {
//didnt work
FundRaiserApplet runme = new FundRaiserApplet();
runme.init();
JPanel container = new JPanel();
container.setLayout(new GridLayout(1,0));
container.add(secondApplet);
add(container);
secondApplet.init();
secondApplet.start();
secondApplet.setVisible(true);
status.setText("Logged in");
// this.dispose();
//FundRaiserApplet.init();
}else{
status.setText("Wrong Username or Password");
}
}
ret.close();
} catch(Exception ex)
{
System.out.println("ERROR: " + ex.getMessage());
}
}
}
}
//MAIN CLASS BELOW////////////////////
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.applet.Applet;
public class FundRaiserApplet extends Applet {
//database creation
// static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
//static final String DB_URL = "jdbc:derby://localhost/";
//end database creation
ArrayList<String> resultsHold = new ArrayList<>();
private JLabel DonorNamelabel;
private JLabel AmountLabel;
private JLabel charityName;
private JLabel emptycell;
static final String USER = "identityone";
static final String PASS = "test";
private JTextField donorNameTexfield;
private JTextField Amounttextfield;
private JTextField singletextfield;
private JTextArea resultsscreen;
public JButton seeAll;
public JButton myExitButton;
public JButton Enter;
public JButton ClearButton;
JPanel centerPanel;
JPanel buttonPanel;
JPanel textfieldPanel;
JPanel myresultsPanel;
JPanel results1Panel;
//JPanel container = new JPanel();
public void init() {
setSize(400, 325);
DonorInfo donor = new DonorInfo();
String[] charityselections = { "Wounded Warrior Project","American Red Cross", "Doctors Without Borders","American Cancer Society","PETA"};
final JComboBox<String> chairtycombo = new JComboBox<>(charityselections);
chairtycombo.setVisible(true);
//creating text fields, labels and buttons
emptycell = new JLabel("");
DonorNamelabel = new JLabel("Donor Name",10);
AmountLabel = new JLabel("Pledge Amount",10);
charityName = new JLabel ("Charity Name",10);
donorNameTexfield = new JTextField(8);
Amounttextfield = new JTextField(8);
singletextfield = new JTextField(35);
resultsscreen = new JTextArea(7, 35);
final JScrollPane myScroll = new JScrollPane(resultsscreen);
myExitButton = new JButton("Exit");
myExitButton.setSize(new Dimension(10, 10));
Enter = new JButton("Enter Info");
Enter.setSize(new Dimension(10, 10));
ClearButton= new JButton("Clear");
ClearButton.setSize(new Dimension(10, 10));
seeAll = new JButton("See All Results");
seeAll.setSize(new Dimension(10, 10));
seeAll.setMargin(new Insets(2, 0, 2, 0));
//adding panels
results1Panel = new JPanel();
centerPanel = new JPanel();
buttonPanel = new JPanel();
textfieldPanel = new JPanel();
myresultsPanel = new JPanel();
//adding labels
centerPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 67, 0));
centerPanel.add(DonorNamelabel);
centerPanel.add(AmountLabel);
centerPanel.add(charityName);
// adding text fields
textfieldPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 30, 3));
textfieldPanel.add(donorNameTexfield);
textfieldPanel.add(Amounttextfield);
textfieldPanel.add(chairtycombo);
//adding the buttons to the panel
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 5));
buttonPanel.add(seeAll);
buttonPanel.add(myExitButton);
buttonPanel.add(Enter);
buttonPanel.add(ClearButton);
myresultsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
myresultsPanel.add(emptycell);
myresultsPanel.add(myScroll);
myresultsPanel.add(emptycell);
myresultsPanel.add(emptycell);
results1Panel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 2));
results1Panel.add(singletextfield);
add(centerPanel, BorderLayout.NORTH);
add(textfieldPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
add(results1Panel, BorderLayout.NORTH);
add(myresultsPanel, BorderLayout.SOUTH);
//clear button action event listener
ClearButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
donorNameTexfield.setText("");
Amounttextfield.setText("");
singletextfield.setText("");
resultsscreen.setText("");
resultsHold.clear();
}
});
//end clear listener
Enter.addActionListener(new ActionListener() {
int counter=1;
#Override
public void actionPerformed(ActionEvent e)
{
singletextfield.setText("");
double amountc = Double.parseDouble(Amounttextfield.getText());
String charityselection = (String) chairtycombo.getSelectedItem();
donor.setName(donorNameTexfield.getText());
donor.setCharityname(charityselection);
donor.setAmount(amountc);
String name = donor.getName();
Double amount = donor.getAmount();
String charity = donor.getCharityName();
String text ="Donor Name is:" +name +"\n"+"Pledge Amount: $" + amount + "\n"+"Charity Name: "+charity+"\n"+"-----------------------------------------------";
//Ading the text variable into array
resultsHold.add(text);
//displaying results in textarea
singletextfield.setText("Donor Name is:" +name +" Pledge Amount: $" + amount + "..." + "Charity Name: "+charity);
try
{
// Create a connection to the database.
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/Fundraiser;user=test;password=test");
Statement stmt = conn.createStatement();
String sqlStatement = "INSERT INTO Fundraiser" +"( NAME, PLEDGE_AMOUNT,CHARITY)" + " VALUES('" + name +"' , " + amount +" , '" + charity +"' )";
stmt.executeUpdate(sqlStatement);
System.out.println("Records Updated.");
// Close the connection.
conn.close();
System.out.println("Connection closed.");
}
catch(Exception ex)
{
System.out.println("ERROR: " + ex.getMessage());
}
// resetting text fields
donorNameTexfield.setText("");
Amounttextfield.setText("");
counter++;
}
});
//event listeners
myExitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
//exit program
System.exit(0);
}
});
seeAll.addActionListener((ActionEvent e) -> {
try{
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/Fundraiser;user=test;password=test");
Statement stmt = conn.createStatement();
String sqlStatement = "SELECT * FROM Fundraiser";
ResultSet result = stmt.executeQuery(sqlStatement);
while (result.next())
{
resultsscreen.append("Pledge Name: " + result.getString("NAME") + "\n"+
"Amount Given: "+result.getDouble("PLEDGE_AMOUNT") +"\n"+
"Donor Charity: " + result.getString("CHARITY")+"\n"+ "........................."+ "\n");
}
// Close the connection.
conn.close();
} catch(Exception ex)
{
System.out.println("ERROR: " + ex.getMessage());
}
//resultsscreen.append(text.toString());
});
}
public static void main(String[] args) {
//database initialization
Connection conn = null;
Connection conn2 = null;
Statement stmt = null;
Statement start = null;
try{
//downloaded driver "mysql-connector-java-5.1.18-bin.jar" and added into project library
//downloaded "derbyclient.jar" and added to library
Class.forName("com.mysql.jdbc.Driver").newInstance ();
//connection time!
System.out.println("Connecting to database...");
//if a folder already exist in "C:\Users\User\.netbeans-derby" called "Fundraiser" then delete it or it will throw an exception
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/Fundraiser;create=true;user=test;password=test");
conn2 = DriverManager.getConnection("jdbc:derby://localhost:1527/Credentials;create=true;user=test;password=test");
//Create database
System.out.println("Fundraiser Database Created!");
stmt = conn.createStatement();
start = conn2.createStatement();
try{
String sql1 = "DROP TABLE Fundraiser";
String dropcreds = "DROP TABLE Credentials";
stmt.executeUpdate(sql1);
System.out.println("Fundraiser Table Deleted...");
start.executeUpdate(dropcreds);
System.out.println("Credentials Table Deleted...");
}catch(Exception e){System.out.println("No Table to Delete...");}
String sql = "CREATE TABLE Fundraiser" +
"(NAME VARCHAR(255), " +
" PLEDGE_AMOUNT DOUBLE, " +
" CHARITY VARCHAR(255) )";
String sql2 = "CREATE TABLE Credentials" +
"(username VARCHAR(255), " +
" password VARCHAR(255) )";
stmt.executeUpdate(sql);
System.out.println("Fundraiser Table created successfully...");
start.executeUpdate(sql2);
System.out.println("Credential Table Created successfully...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException my2){
System.out.println(my2);
}
try{
if(conn!=null)
conn.close();
}catch(SQLException my){
my.printStackTrace();
}
}//end try
FundRaiserApplet applet = new FundRaiserApplet();
applet.init();
JFrame frame = new JFrame("Identity One");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( applet );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
applet.start();
//login.main(args);
}
public void ShowWindow() {
FundRaiserApplet applet = new FundRaiserApplet();
applet.init();
JFrame frame = new JFrame("My Program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( applet );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
applet.start();
}
}
You can try to use javascript to open the second applet in the web page.
This is the coding on a button of jFrame a simple login form, username and password authentication working fine but if else condition dont execute i am stuck here if any of you guys help me out here just give me a hint
String u_id=jTextField1.getText();
String p_word=jPasswordField1.getText();
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con=DriverManager.getConnection("jdbc:sqlserver://localhost:1433; databaseName=LoginForm; user=sa; password=aptech");
Statement st=con.createStatement();
ResultSet result=st.executeQuery("select pass_word from employee where user_name='"+u_id+"' ");
if(result.next())
{
String pwd = result.getString("pass_word");
if( p_word.equals(pwd))
{
jLabel4.setText("you are logged in");
}
else if (!p_word.equals(pwd))
{
jLabel4.setText("Your id password is Wrong");
}
}
else
{
jLabel4.setText("Enter your id password again");
jTextField1.setText("");
jPasswordField1.setText("");
}
}
catch (ClassNotFoundException a)
{
System.out.println(""+a);
}
catch (SQLException s)
{
System.out.println(""+s);
}
Try this one instead:
Create a new class called (I hope you're using and IDE!) "Log.java"
Copy & Paste following code into the class.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Log extends JFrame {
public static void main(String[] args) {
Log frameTable = new Log();
}
JButton Login = new JButton("Login");
JPanel panel = new JPanel();
JTextField txuser = new JTextField(15);
JPasswordField pass = new JPasswordField(15);
Log(){
super("Login Autentification");
setSize(300,200);
setLocation(500,280);
panel.setLayout (null);
txuser.setBounds(70,30,150,20);
pass.setBounds(70,65,150,20);
Login.setBounds(110,100,80,20);
panel.add(Login);
panel.add(txuser);
panel.add(pass);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
actionlogin();
}
public void actionlogin(){
Login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String puname = txuser.getText();
String ppaswd = pass.getText();
if(puname.equals("1") && ppaswd.equals("2")) {
newframe regFace =new newframe();
regFace.setVisible(true);
dispose();
} else {
JOptionPane.showMessageDialog(null,"Wrong Password or Username!");
txuser.setText("");
pass.setText("");
txuser.requestFocus();
}
}
});
}
}
Then, create a new class, "newframe.java", and fill it with this code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class newframe extends JFrame {
public static void main(String[] args) {
newframe frameTabel = new newframe();
}
JLabel welcome = new JLabel("Welcome to a New Frame");
JPanel panel = new JPanel();
newframe(){
super("Welcome");
setSize(300,200);
setLocation(500,280);
panel.setLayout (null);
welcome.setBounds(70,50,150,60);
panel.add(welcome);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
Now you should be good to go, if something is not clear, feel free to ask or figure out by yourself, this lovely community will try to help.
You have about ten time more code than you need. Do this instead (pseudo code):
Use this query instead:
select count(*)
from employee
where user_name = ?
and pass_word = ?
You will get exactly one row with one column returned.
The value of that column will be either 1 or 0
You should be able to handle the rest by yourself.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I don't know much about SQL, but I'm fine with Java, I just wanted to know how I can retrieve a variable from my SQL database: 'EasyDirectory'. Like:
String test = con.getQuery(query1).get(username);
Obviously that doesn't work but I would like a snippet of code that does that. Heres all of my code:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
public class Directory {
public static void main(String args[]) throws IOException, SQLException {
Connection con = null;
try {
// Load the JDBC driver
String driverName = "org.gjt.mm.mysql.Driver"; // MySQL MM JDBC driver
Class.forName(driverName);
// Create a connection to the database
String serverName = "www.freesql.org";
String mydatabase = "EasyDirectory";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url
String username = "*********";
String password = "*********";
con = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
// Could not find the database driver
} catch (SQLException e) {
// Could not connect to the database
}
final JFrame frame = new JFrame("Directory");
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JProgressBar searchprogress = new JProgressBar();
final JPanel panel = new JPanel();
final JButton searchbutton = new JButton("Search");
final JTextField searchfield = new JTextField();
searchfield.setPreferredSize(new Dimension(200, 30));
searchprogress.setPreferredSize(new Dimension(280, 30));
searchbutton.setLocation(100, 100);
/* Start Buffered Reader */
final List<String> housetypes = new ArrayList<String>();
String line = "";
BufferedReader br = new BufferedReader(new FileReader("Index.txt"));
while (line != null) {
line = br.readLine();
housetypes.add(line);
String seperation = br.readLine();
}
/* Finish Buffered Reader */
/* Start Content Code */
final JButton done = new JButton("Done");
done.setVisible(false);
JLabel housetype_label = new JLabel();
JLabel housenumber_label = new JLabel();
JLabel housestreet_label = new JLabel();
JLabel housepostal_label = new JLabel();
JLabel houseplace_label = new JLabel();
/* Finish Content Code */
/* Start Button Code */
done.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
searchfield.setEnabled(true);
done.setVisible(false);
searchbutton.setVisible(true);
searchprogress.setValue(0);
}
});
searchbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
searchprogress.setValue(100);
String searchquery = searchfield.getText();
searchprogress.setValue(100);
searchfield.setEnabled(false);
done.setVisible(true);
searchbutton.setVisible(false);
for (String housetype : housetypes) {
if (searchquery.equals(housetype)) {
String housepath = housetype + "/" + housetype + ".txt";
System.out.println(housepath);
try {
BufferedReader housebr = new BufferedReader(new FileReader(housepath));
String housename_query = housebr.readLine();
String housenumber_query = housebr.readLine();
String housestreet_query = housebr.readLine();
String houselocality_query = housebr.readLine();
String housepostal_query = housebr.readLine();
System.out.println(housepostal_query);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
/* Finish Button Code */
/* Test Field */
/* End Test Field */
panel.add(searchfield);
panel.add(done);
panel.add(searchbutton);
panel.add(searchprogress);
frame.setResizable(false);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(false);
/* Start Login Window */
int passtimes = 3;
final JFrame login = new JFrame("Login");
JPanel login_panel = new JPanel();
JLabel userlabel = new JLabel("Username: ");
JLabel passlabel = new JLabel(" Password: ");
JButton loginuser = new JButton("Login");
JButton cancel = new JButton("Cancel");
final JTextField user_field = new JTextField();
user_field.setPreferredSize(new Dimension(100,30));
final JPasswordField pass_field = new JPasswordField();
pass_field.setPreferredSize(new Dimension(100,30));
ImageIcon icon = new ImageIcon("Images/Logo.png");
ImageIcon space = new ImageIcon("Images/Spacing.png");
JLabel logo = new JLabel();
JLabel spacing = new JLabel();
logo.setIcon(icon);
login.setPreferredSize(new Dimension(200,212));
login_panel.add(logo);
login_panel.add(userlabel);
login_panel.add(user_field);
login_panel.add(passlabel);
login_panel.add(pass_field);
login_panel.add(spacing);
login_panel.add(loginuser);
login_panel.add(cancel);
login.add(login_panel);
login.pack();
login.setVisible(true);
login.setLocationRelativeTo(null);
loginuser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String user_input = user_field.getText();
String pass_input = pass_field.getText();
String username = "Tom";
String password = "******";
if(user_input.equals(username)){
if(pass_input.equals(password)){
user_field.setEnabled(false);
pass_field.setEnabled(false);
frame.setVisible(true);
login.setVisible(false);
}
else{//If Password AND Username is incorrect
JOptionPane.showMessageDialog(panel, "Password and/or Username Is Incorrect.", "Failed Login", JOptionPane.ERROR_MESSAGE);
}
}
else{ //If Username is incorrect
JOptionPane.showMessageDialog(panel, "Password and/or Username Is Incorrect.", "Failed Login", JOptionPane.ERROR_MESSAGE);
}
}
});
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
}
}
Thanks, Helping is greatly appreciated!
By reading the API of Connection (here: http://docs.oracle.com/javase/6/docs/api/java/sql/Connection.html) I would assume that it would have to be something like:
final Statement statement = con.createStatement();
final ResultSet result = statement.executeQuery(query1);
//do stuff with the resultset
//result.getString(something), see http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html
On a side-note. I don't really like the fact that you have put both the GUI and the database logic in the same class. You really should separate concerns, by applying the MVC pattern or something similar. For instance, you could create one class for the GUI, one class for to the connection the database, and one class for starting the application and tying the two others together.
Sorry last program had lot of errors (i forgot to save the file and hence posted a incomplete code) so i am posting this
Here is the Code:
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUIPreparedStatement {
private JFrame frame1;
private JPanel panel1;
private JTextField tf1;
private JTextField tf2;
private JButton b1;
public JLabel lb1;
PreparedStatement ps;
GUIPreparedStatement() {
frame1 = new JFrame();
panel1 = new JPanel();
tf1 = new JTextField(10);
tf2 = new JTextField(10);
b1 = new JButton("Enter Record");
lb1 = new JLabel("Press the Button");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Employees");
ps = con.prepareStatement("INSERT INTO Employees VALUES(?,?)");
} catch(SQLException e) {
lb1.setText("SQL Statement not executed");
} catch(Exception e) {
lb1.setText("General Error");
}
b1.addActionListener(this);
panel1.add(tf1);
panel1.add(tf2);
panel1.add(b1);
panel1.add(lb1);
Container contentPane = frame1.getContentPane();
contentPane.add(panel1);
frame1.setDefaultCloseOperation(frame1.EXIT_ON_CLOSE);
frame1.setVisible(true);
frame1.pack();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
try {
ps.setString(1,tf1.getText());
ps.setString(2,tf2.getText());
ps.executeUpdate();
} catch (SQLException f) {
lb1.setText("SQL Record not Entered");
}
}
}
public static void main (String args[]) {
new GUIPreparedStatement();
}
}
Error in code:
http://screensnapr.com/u/nx5t1r.png
To answer your heavily edited question, your GUIPreparedStatment needs to implement the ActionListener interface.
public class GUIPreparedStatement implements ActionListener
Whilst you have already implemented the actionPerformed(ActionEvent e) you have not declared to the compiler that you've done this to satisfy the interface contract.
Some of your your errors are referencing lines of code which you did not post.
EDIT: Corrected assumptions which were invalid