Java wrong username & password message cant seem to work - java

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.

Related

JFrame window is not closing

so i was trying to make a quiz application but i got this error below
I Want to close the JFrame window so i tried setVisible(false); to close window if someone click back button but it is not working help me as im new. i even tried Jframe.dispose(); and other methods i dont what error i have made if you help me pls
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Login extends JFrame implements ActionListener {
JButton Rules,Back;
Login() {
getContentPane().setBackground(Color.white);
ImageIcon i1 = new ImageIcon(ClassLoader.getSystemResource("icon/login.jpeg"));//<-- to pick images from directory
setLayout(null);
JLabel image = new JLabel(i1);
JLabel heading = new JLabel("Quiz Bazzi");
heading.setBounds(750,50,300,50);
heading.setFont(new Font("Mongolian Baiti",Font.BOLD,42));
heading.setForeground(Color.ORANGE);
add(heading);
JLabel name = new JLabel("Enter Your Name");
name.setBounds(785,150,350,20);
name.setFont(new Font("Mongolian Baiti",Font.BOLD,18));
name.setForeground(Color.black);
add(name);
JTextField tfname = new JTextField();
tfname.setBounds(715,180,300,25);
tfname.setFont(new Font("Times New Roman",Font.BOLD,18));
tfname.setForeground(Color.black);
add(tfname);
Rules = new JButton("Rules");
Rules.setBounds(715,220,120,25);
Rules.setBackground(Color.black);
Rules.setForeground(Color.white);
add(Rules);
Back = new JButton("Back");
Back.setBounds(895,220,120,25);
Back.setBackground(Color.black);
Back.setForeground(Color.white);
add(Back);
image.setBounds(0,0,500,400);
add(image);
setSize(1200,439);
setLocation(180,100);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == Rules){
setVisible(true);
} else if (e.getSource() == Back) {
setVisible(false);
}
}
public static void main(String[] args) {
new Login();
}
}
Do you know what it the purpose of:
JFrame.dispose();
?
It is exactly what you need :)

How to insert image to existing JFrame

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.

Close one JFrame before opening another JFrame

I want to close completely one JFrame before opening another .
Consider the code :
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
/**
*
* #author X
*
*/
class ServerConnect extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
private JTextField m_serverIP;
private JTextField m_serverPort; // you can use also JPasswordField
private JButton m_submitButton;
// location of the jframe
private final int m_centerX = 500;
private final int m_centerY = 300;
// dimensions of the jframe
private final int m_sizeX = 1650;
private final int m_sizeY = 150;
/**
* Ctor
*/
ServerConnect()
{
this.setTitle("Sever Side Listener");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
m_serverIP = new JTextField(20);
m_serverPort = new JTextField(20);
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
gui.setSize(m_sizeX , m_sizeY);
this.setContentPane(gui);
JPanel labels = new JPanel(new GridLayout(0,1));
JPanel controls = new JPanel(new GridLayout(0,1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Server IP: "));
controls.add(m_serverIP);
labels.add(new JLabel("Server Port: "));
controls.add(m_serverPort);
m_submitButton = new JButton("Start Listening");
m_submitButton.addActionListener(this);
gui.add(m_submitButton, BorderLayout.SOUTH);
this.setLocation(m_centerX , m_centerY);
this.setSize(m_sizeX , m_sizeY);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new ServerConnect();
}
#Override
public void actionPerformed(ActionEvent event) {
Object object = event.getSource();
if (object == this.m_submitButton)
{
// grab all values from the connection box
// if one of them is missing then display an alert message
String ip = this.m_serverIP.getText().trim();
String port = this.m_serverPort.getText().trim();
if (ip.length() == 0)
{
JOptionPane.showMessageDialog(null, "Please enter IP address !");
return;
}
if (port.length() == 0)
{
JOptionPane.showMessageDialog(null, "Please enter Port number!");
return;
}
int s_port = 0;
try
{
// try parse the Port number
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
s_port = Integer.parseInt(port);
}
catch(Exception exp)
{
JOptionPane.showMessageDialog(null, "Port number is incorrect!");
return;
}
try
{
// try parse the IP address
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
InetAddress.getByName(ip);
}
catch(Exception exp)
{
JOptionPane.showMessageDialog(null, "IP address is incorrect!");
return;
}
this.setVisible(false);
new ServerGUI(ip , s_port);
}
}
}
In actionPerformed() after the user had entered the IP number and port , I set the window to false , i.e :
this.setVisible(false); // don't show the current window
new ServerGUI(ip , s_port); // open another JFrame
I want to close the current JFrame completely, not to set its visibility to false.
How can I do that ?
Regards
Your problem appears that if you call close on the JFrame, the program will exit since you've set its setDefaultCloseOperation to setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);.
Options:
Use a different defaultCloseOperation, one that doesn't close the application, perhaps JFrame.DISPOSE_ON_CLOSE.
Use a JDialog initially instead of a JFrame. These types of windows can't shut down the application. Here is the JDialog and JOptionPane Tutorial
Don't swap JFrames at all, but rather swap views by using a CardLayout. The CardLayout Tutorial link
My own preference is to use a CardLayout as much as possible to avoid annoying the user who usually doesn't appreciate having a bunch of windows flung at him. I also use modal JDialogs when I want to get information from the user in a modal fashion, i.e., where the application absolutely cannot move forward until the user gives the requested information, and non-modal dialogs to present program state monitoring information for the user. I almost never use multiple JFrames in a single application.
Edit
As an aside, I almost never create classes that extend JFrame or any top-level window since I find that much too restricting. Instead most of my GUI type classes are geared towards creating JPanels. The advantage to this is then I can decide when and where I want to put the JPanel, and can change my mind at any time. It could go into a JFrame, a JDialog, a JOptionPane, be a card that is swapped in a CardLayout,... anywhere.
Edit 2
For example, here's a small program that uses your code, slightly modified, and puts it into a JDialog:
My code:
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class MyServerMain extends JPanel {
private JTextField serverIp = new JTextField(8);
private JTextField serverPort = new JTextField(8);
private ServerConnect serverConnect = new ServerConnect();
private JDialog serverConnectDialog = null;
public MyServerMain() {
serverIp.setFocusable(false);
serverPort.setFocusable(false);
add(new JLabel("Server IP:"));
add(serverIp);
add(new JLabel("Server Port:"));
add(serverPort);
add(new JButton(new SetUpServerAction("Set Up Server", KeyEvent.VK_S)));
}
private class SetUpServerAction extends AbstractAction {
public SetUpServerAction(String name, int keyCode) {
super(name);
putValue(MNEMONIC_KEY, keyCode);
}
#Override
public void actionPerformed(ActionEvent evt) {
if (serverConnectDialog == null) {
Window owner = SwingUtilities.getWindowAncestor(MyServerMain.this);
serverConnectDialog = new JDialog(owner, "Server Set Up",
ModalityType.APPLICATION_MODAL);
serverConnectDialog.getContentPane().add(serverConnect);
serverConnectDialog.pack();
serverConnectDialog.setLocationRelativeTo(owner);
}
serverConnectDialog.setVisible(true);
// when here, the dialog is no longer visible
// so extract information from the serverConnect object
serverIp.setText(serverConnect.getServerIp());
serverPort.setText(serverConnect.getServerPort());
}
}
private static void createAndShowGui() {
MyServerMain mainPanel = new MyServerMain();
JFrame frame = new JFrame("My Server Main");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Your modified code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class ServerConnect extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField m_serverIP;
private JTextField m_serverPort; // you can use also JPasswordField
private JButton m_submitButton;
// location of the jframe
private final int m_centerX = 500;
private final int m_centerY = 300;
// dimensions of the jframe
private final int m_sizeX = 1650;
private final int m_sizeY = 150;
ServerConnect() {
m_serverIP = new JTextField(20);
m_serverPort = new JTextField(20);
JPanel gui = new JPanel(new BorderLayout(3, 3));
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
gui.setSize(m_sizeX, m_sizeY);
setLayout(new BorderLayout()); // !!
add(gui, BorderLayout.CENTER);
JPanel labels = new JPanel(new GridLayout(0, 1));
JPanel controls = new JPanel(new GridLayout(0, 1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Server IP: "));
controls.add(m_serverIP);
labels.add(new JLabel("Server Port: "));
controls.add(m_serverPort);
m_submitButton = new JButton("Start Listening");
m_submitButton.addActionListener(this);
gui.add(m_submitButton, BorderLayout.SOUTH);
this.setLocation(m_centerX, m_centerY);
this.setSize(m_sizeX, m_sizeY);
// !! this.pack();
// !! this.setVisible(true);
}
public static void main(String[] args) {
new ServerConnect();
}
#Override
public void actionPerformed(ActionEvent event) {
Object object = event.getSource();
if (object == this.m_submitButton) {
// grab all values from the connection box
// if one of them is missing then display an alert message
String ip = this.m_serverIP.getText().trim();
String port = this.m_serverPort.getText().trim();
if (ip.length() == 0) {
JOptionPane.showMessageDialog(null, "Please enter IP address !");
return;
}
if (port.length() == 0) {
JOptionPane.showMessageDialog(null, "Please enter Port number!");
return;
}
int s_port = 0;
try {
// try parse the Port number
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
s_port = Integer.parseInt(port);
}
catch (Exception exp) {
JOptionPane.showMessageDialog(null, "Port number is incorrect!");
return;
}
try {
// try parse the IP address
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
InetAddress.getByName(ip);
}
catch (Exception exp) {
JOptionPane.showMessageDialog(null, "IP address is incorrect!");
return;
}
// !! this.setVisible(false);
// !! new ServerGUI(ip , s_port);
// !!
Window ownerWindow = SwingUtilities.getWindowAncestor(this);
ownerWindow.dispose();
}
}
// !!
public String getServerIp() {
return m_serverIP.getText();
}
// !!
public String getServerPort() {
return m_serverPort.getText();
}
}
Hope this another_Frame frm = new another_Frame();
frm.setVisible(true);
this.dispose();// this represent the fram to close

Which timer to use for GUI in Java

I have been trying to find the best timer to use for the following code (note this is a simplified version of my overall program). My hope is to run a method after 3 seconds.
The problem is with the actionPerformed, checkBlankLogin, and resetLoginBlank and putting a timer to delay resetLoginBlank from happening 3 seconds after checkBlankLogin has happened. But I want all methods in the class Outerframe to continuously run. So checkBlankLogin will keep checking if its blank until the person inputs the information for a "Valid Input" and the Login innerframe will close. But I don't know how to do that... Any help there also?
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
import java.io.*;
import java.io.File;
import java.util.*;
import java.io.FileNotFoundException;
class OuterFrame extends JFrame implements ActionListener
{
Container pane; // container
JDesktopPane outframe; // outer frame
JInternalFrame login; // login frame
//pieces of login frame
JLabel loginLBLtitle;
JPanel loginPanel;
JLabel loginLBLname;
JLabel loginBlankName;
JLabel loginLBLpass;
JLabel loginBlankPass;
JTextField loginTXT;
JPasswordField loginPASS;
JButton loginBUT;
JInternalFrame apple;
OuterFrame()
{
//set up for Outer Frame
super("Application");
setSize(450,240);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
outframe = new JDesktopPane();
outframe.setBackground(Color.BLUE);
//set up for Container
pane = getContentPane();
setContentPane(pane);
pane.add(outframe);
//Login Inner Frame
login = new JInternalFrame();
login.setSize(400,200);
login.setLocation(20,20);
login.setTitle("Member Login");
loginLBLtitle = new JLabel("Sign in with netid and your password.");
Font loginFontbody = new Font("SansSerif", Font.PLAIN, 12);
Font loginFonthead = new Font("SansSerif", Font.BOLD, 13);
loginLBLtitle.setFont(loginFonthead);
loginLBLname=new JLabel("User Name:");
loginLBLname.setFont(loginFontbody);
loginLBLpass=new JLabel("Password: ");
loginLBLpass.setFont(loginFontbody);
loginBUT=new JButton("Login");
loginBUT.setFont(loginFontbody);
loginBUT.addActionListener(this);
loginTXT=new JTextField(20);
loginPASS=new JPasswordField(20);
loginBlankName=new JLabel("");
loginBlankPass=new JLabel("");
loginPanel=new JPanel();
loginPanel.add(loginLBLtitle);
loginPanel.add(loginLBLname);
loginPanel.add(loginTXT);
loginPanel.add(loginBlankName);
loginPanel.add(loginLBLpass);
loginPanel.add(loginPASS);
loginPanel.add(loginBlankPass);
loginPanel.add(loginBUT);
//panel.add(lblmess);
login.add(loginPanel);
login.setVisible(true);
//Add Login to Outer Frame
outframe.add(login);
outframe.setSelectedFrame(login);
pane.add(outframe, BorderLayout.CENTER);
setVisible(true);
loginTXT.requestFocus();
}
public void actionPerformed(ActionEvent e)
{
//problem area
if(e.getSource()==loginBUT)
{
String uname=loginTXT.getText();
String passw=new String(loginPASS.getPassword());
int i=0;
while(i!=5)
{
if(checkBlankLogin(uname,passw,loginBlankName,loginBlankPass))
{
resetLoginBlank(loginBlankName,loginBlankPass);
}
else
{
if(!validateUser("accounts.txt",uname,passw,loginLBLtitle))
{
}
}
}
}
public void resetLoginBlank(JLabel loginBlankName, JLabel loginBlankPass)
{
loginBlankName.setText("");
loginBlankPass.setText("");
}
public void resetLoginTitle(JLabel loginBlankTitle)
{
loginBlankTitle.setText("Sign in with netid and your password.");
loginBlankTitle.setForeground(Color.BLACK);
}
public boolean checkBlankLogin(String name, String passw, JLabel loginBlankName, JLabel loginBlankPass)
{
boolean isBlank=false;
if(name.length()<1)
{
loginBlankMess("User name is required.",loginBlankName);
isBlank=true;
}
if(passw.length()<1)
{
loginBlankMess("Password is required.",loginBlankPass);
isBlank=true;
}
return isBlank;
}
public void loginBlankMess(String mess, JLabel lbl)
{
lbl.setText(mess);
lbl.setForeground(Color.RED);
}
public boolean validateUser(String filename, String name, String password, JLabel title)
{
boolean valid = false;
try
{
File file = new File(filename);
Scanner scanner = new Scanner(file);
ArrayList<String> fileInfo = new ArrayList<String>();
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
fileInfo.add(line);
}
String fullLogin = name + " " + password;
if(fileInfo.contains(fullLogin))
{
//loginBlankMess("Valid login",namemess);
valid=true;
}
if(!valid)
{
loginBlankMess("Please enter valid netid and password.", title);
resetLoginTitle(title);
}
}
catch(Exception ie)
{
System.exit(1);
}
return valid;
}
}
public class TheProgram
{
public static void main(String[] args)
{
new OuterFrame();
}
}`
I would check out the following resource (assuming you using Swing for your UI):
How to Use Swing Timers (Oracle)
Swing timers are the easiest in your case. You make your class implement ActionListener, and create a timer object. The timer will call the actionPerformed method when it expires.
import javax.swing.Timer;
class OuterFrame extends JFrame implements ActionListener{
Timer timer = null;
public void actionPerformed(ActionEvent e) {
if(e.getSource()==loginBUT){
//If the action came from the login button
if (checkBlankLogin()){
timer = new Timer(3000, this);
timer.setRepeats(false);
timer.setInitialDelay(3000);
timer.start();
} else if (timer != null){
timer.stop();
}
}else if(e.getSource()==timer){
//If the action came from the timer
resetLoginBlank(namemess,passwmess));
}
}
}

Why am I getting an error when trying to add an action listener to a button?

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

Categories