/*this is my java code which when i compile they don not show exactly error */
public class Login {
public JFrame frame;
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();
}
}
});
}
Connection conections;
private JTextField textField;
private JPasswordField passwordField;
public Login() {
initialize();
conections = SqliteConnectio.dbConnection();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 581, 411);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(266, 112, 193, 45);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnLOGIN = new JButton("LOGIN");
Image jn=new ImageIcon(this.getClass().getResource("/Ok.png")).getImage();
btnLOGIN.setIcon(new ImageIcon(jn));
btnLOGIN.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select *from customer.sqlite where username=? and password=? ";
PreparedStatement pre = conections.prepareStatement(query);
pre.setString(1, textField.getText());
pre.setString(2, passwordField.getText());
ResultSet res = pre.executeQuery();
int count = 0;
while (res.next()) {
count++;
}
if (count == 1) {
JOptionPane.showInternalMessageDialog(null, "username and password has sucseeful inserted");
} else if (count > 1) {JOptionPane.showInternalMessageDialog(null, "username and password has sucseeful inserted");
}
else {
JOptionPane.showInternalMessageDialog(null, "username and password has been failed to be entered");
}
res.close();
pre.close();
} catch (Exception e) {
JOptionPane.showInternalMessageDialog(null, "you have failed to asses the database");
}
}
});
btnLOGIN.setBounds(321, 256, 125, 36);
frame.getContentPane().add(btnLOGIN);
JLabel userNAME = new JLabel("USERNAME");
userNAME.setBounds(156, 127, 85, 14);
frame.getContentPane().add(userNAME);
JLabel passLABEL = new JLabel("PASSWORD");
passLABEL.setBounds(156, 191, 85, 14);
frame.getContentPane().add(passLABEL);
passwordField = new JPasswordField();
passwordField.setBounds(266, 188, 193, 20);
frame.getContentPane().add(passwordField);
JLabel lblNewLabel = new JLabel("New label");
Image im=new ImageIcon(this.getClass().getResource("/login.png")).getImage();
lblNewLabel.setIcon(new ImageIcon(im));
lblNewLabel.setBounds(10, 21, 136, 205);
frame.getContentPane().add(lblNewLabel);
}
}
//this is my connection to database which it seems to work just fine by prompting "username and password has sucseeful inserted"
package mi;
import java.sql.*;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SqliteConnectio {
Connection conect=null;
public static Connection dbConnection(){
try {
Class.forName("org.sqlite.JDBC");
Connection conect=DriverManager.getConnection(
"jdbc:sqlite:E:\\JAVA WORLD\\sgliteDatabase\\customer.sqlite");
JOptionPane.showMessageDialog(null, "sucessful login to database");
return conect;
} catch (Exception e) {
JOptionPane.showConfirmDialog(null, "failed to login in database");
return null;
}
}
}
Related
I am implementing a search interface in eclipse with the help of mysql. My search interface yields the results I want, but I want to be able to have the "video_url" column clickable and bring up a hyperlink. Is there a way to do this for a single column? Right now the Jtable is "editable", so the user can click on it, but no changes are made to it. The link can be copied and then pasted later, but I'm really trying to have the link be opened from the interface.
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
VIdeo_search_test window = new VIdeo_search_test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public VIdeo_search_test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 17));
frame.setBounds(400, 400, 1050, 1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblVideoSearch = new JLabel("Video Search");
lblVideoSearch.setFont(new Font("Tahoma", Font.PLAIN, 19));
lblVideoSearch.setBounds(241, 11, 230, 27);
frame.getContentPane().add(lblVideoSearch);
JButton btnSearchCity = new JButton("Search City");
btnSearchCity.setBounds(216, 80, 165, 25);
btnSearchCity.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = new DefaultTableModel(new String[]{"video_url", "video name", "video description", "video_city", "video_subject", "video_tags", "reviewed_by", "star"}, 0);
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 video where video_city = '" +txtCity.getText()+"'";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
String a = rs.getString("video_url");
String d = rs.getString("video_name");
String e = rs.getString("video_description");
String f = rs.getString("video_city");
String g = rs.getString("video_subject");
String h = rs.getString("video_tags");
String k = rs.getString("reviewed_by");
String i = rs.getString("star");
model.addRow(new Object[]{a, d, e, f, g, h, k, i});
table.setModel(model);
}
{
con.close();}
} catch(Exception e) {System.out.print (e);}
}
});
frame.getContentPane().add(btnSearchCity);
JButton btnSearchTag = new JButton("Search Tag");
btnSearchTag.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = new DefaultTableModel(new String[]{"video_url", "video name", "video description", "video_city", "video_subject", "video_tags", "reviewed_by", "star"}, 0);
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 video where video_tags LIKE '"+txtTag.getText()+"%'";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
String a = rs.getString("video_url");
String d = rs.getString("video_name");
String e = rs.getString("video_description");
String f = rs.getString("video_city");
String g = rs.getString("video_subject");
String h = rs.getString("video_tags");
String k = rs.getString("reviewed_by");
String i = rs.getString("star");
model.addRow(new Object[]{a, d, e, f, g, h, k, i});
table_1.setModel(model);
}
{
con.close();}
} catch(Exception e) {System.out.print (e);}
}
});
btnSearchTag.setBounds(216, 303, 165, 25);
frame.getContentPane().add(btnSearchTag);
txtCity = new JTextField();
txtCity.setBounds(216, 49, 165, 20);
frame.getContentPane().add(txtCity);
txtCity.setColumns(10);
table = new JTable();
table.setBounds(10, 116, 867, 135);
frame.getContentPane().add(table);
txtTag = new JTextField();
txtTag.setColumns(10);
txtTag.setBounds(216, 272, 165, 20);
frame.getContentPane().add(txtTag);
table_1 = new JTable();
table_1.setBounds(10, 341, 601, 135);
frame.getContentPane().add(table_1);
JButton btnViewVideo = new JButton("View Video");
btnViewVideo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
registered_video_interface info = new registered_video_interface();
registered_video_interface.main(null); }
});
btnViewVideo.setBounds(251, 509, 89, 23);
frame.getContentPane().add(btnViewVideo);
}
}
When I try to access data from SQL Server, the data column is of type varchar. But I try to set it into textbox, I got these type of exception
Conversion failed when converting the varchar value '09ran01' to data type int
package src.ui;
import src.ui.ImageHandler;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.event.*;
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.DateFormat;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class AddAccount extends JPanel implements ActionListener, DocumentListener, KeyListener {
String imagefolder = ImageHandler.returnimagepath();
Image bgImage = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/src/ui/images/bgc.jpg"));
private static final long serialVersionUID = 1L;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
String iden[] = {"Student","Others"};
String type[] = {"Account User", "Walkthrough User"};
JLabel userid = new JLabel("USER ID");
JLabel name = new JLabel("FULL NAME");
JLabel pswrd = new JLabel("PASSWORD");
JLabel ident = new JLabel("IDENTIFICATION");
JLabel idno = new JLabel("ID NUMBER");
JLabel Add = new JLabel("ADDRESS");
JLabel acctype = new JLabel("ACCOUNT TYPE");
JTextField userFld = new JTextField(10);
JTextField nameFld = new JTextField(10);
JPasswordField pswrdFld = new JPasswordField(10);
JComboBox identC = new JComboBox(iden);
JComboBox actype = new JComboBox(type);
JTextField idFld = new JTextField(10);
JTextArea addArea = new JTextArea(10, 10);
JButton okButton = new JButton("OK");
JButton exitButton = new JButton("RESET");
JButton b1 = new JButton("SEARCH");
JScrollPane scroll = new JScrollPane(addArea);
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1/cybman", "root", "");
} catch (Exception e) {
//System.out.println(e);
}
return conn;
}
public static Connection getConnection1() {
Connection con = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://localhost\\BCA1:1433;databaseName=Old_Bhandarkars;user=sa;password=1234");
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"SERVER ERROR");
//System.out.println(e);
}
return con;
}
public void changedUpdate(DocumentEvent ev) {
}
public void removeUpdate(DocumentEvent ev) {
}
public void insertUpdate(DocumentEvent ev) {
}
public void paintComponent(Graphics g) {
g.drawImage(bgImage, 0, 0, this);
}
public void init() {
setLayout(null);
okButton.addActionListener(this);
b1.addActionListener(this);
exitButton.addActionListener(this);
pswrdFld.addActionListener(this);
pswrdFld.setEchoChar('*');
addArea.getDocument().addDocumentListener(this);
identC.addActionListener(this);
actype.addActionListener(this);
userid.setBounds(270, 20, 120, 20);
userFld.setBounds(470, 20, 140, 20);
b1.setBounds(670, 20, 100, 20);
name.setBounds(270, 70, 120, 20);
nameFld.setBounds(470, 70, 140, 20);
pswrd.setBounds(270, 120, 120, 20);
pswrdFld.setBounds(470, 120, 140, 20);
ident.setBounds(270, 170, 120, 20);
identC.setBounds(470, 170, 140, 20);
idno.setBounds(270, 220, 120, 20);
idFld.setBounds(470, 220, 140, 20);
acctype.setBounds(270, 270, 120, 20);
actype.setBounds(470, 270, 140, 20);
Add.setBounds(270, 320, 320, 20);
scroll.setBounds(470, 320, 140, 60);
okButton.setBounds(270, 410, 100, 20);
okButton.addKeyListener(this);
exitButton.setBounds(510, 410, 100, 20);
}
public AddAccount() {
init();
add(userid);
add(userFld);
add(name);
add(nameFld);
add(pswrd);
add(pswrdFld);
add(ident);
add(identC);
add(idno);
add(idFld);
add(acctype);
add(actype);
add(Add);
add(b1);
add(scroll);
add(okButton);
add(exitButton);
}
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
public class Function
{
Connection con=getConnection1();
ResultSet rs;
public ResultSet find(String s)
{
int a=Integer.parseInt(s);
try{
Statement sta = con.createStatement();
String s1 = "select * from Members where Fld_Member_Id="+a+"";
rs = sta.executeQuery(s1);
}
catch(Exception ex){
JOptionPane.showMessageDialog(null,"No connection");
//JOptionPane.showMessageDialog(null,ex.getMessage());
}
//JOptionPane.showMessageDialog(null,rs);
return rs;
}
}
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
char[] pass;
String uid;
String nam;
String add;
String id;
String idnum;
String actyp;
int amt = 0;
String datE;
if (str.equals("SEARCH")) {
Function f=new Function();
ResultSet rs=null;
String n1="Fld_First_Name";
String i1="Fld_Member_Id";
String address="Fld_PAddr";
uid = userFld.getText();
if(uid.equals(""))
{
JFrame msg=new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the user id", "Error Message", JOptionPane.ERROR_MESSAGE);
}
// simple.main();
else
{
//idFld.setText(userFld.getText());
rs=f.find(userFld.getText());
// System.out.println("Fld_First_Name");
try{
if(rs.next()){
// int i = Integer.parseInt(rs.getString("Fld_First_Name"));
// int j = Integer.parseInt(rs.getString("Fld_Member_Id"));
// int k = Integer.parseInt(rs.getString("Fld_PAddr"));
nameFld.setText(rs.getString("Fld_First_Name"));
idFld.setText(rs.getString("Fld_Member_Id"));
addArea.setText(rs.getString("Fld_PAddr"));
}
else
{
JOptionPane.showMessageDialog(null,"No data");
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
}
if (str.equals("OK")) {
try {
uid = userFld.getText();
nam = nameFld.getText();
pass = pswrdFld.getPassword();
add = addArea.getText();
idnum = idFld.getText();
id = (String) identC.getSelectedItem();
actyp = (String) actype.getSelectedItem();
datE = getDateTime();
String pwrd = new String(pass);
Connection conn = getConnection();
/*ERROR CHECKING*/
boolean success = true;
if (uid.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the user id", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if (nam.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the name", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if (pwrd.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the password", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if ((!id.equals("Student")) && (idnum.equals(""))) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the identification number", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if (add.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the address", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
}
/*end of ERROR CHECKING*/
if (success == true) {
///////////ENSURE/////////
JFrame msg = new JFrame();
int choice;
choice = JOptionPane.showConfirmDialog(msg, "Are you sure?", "Select your choice", JOptionPane.OK_CANCEL_OPTION);
/////////////////////////
if (choice == JOptionPane.OK_OPTION) {
str = "insert into account(userid,name,password,address,identification,identificationnum,amount,dates,acctype" + ") values (?,?,?,?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(str);
ps.setString(1, uid);
ps.setString(2, nam);
ps.setString(3, pwrd);
ps.setString(4, add);
ps.setString(5, id);
ps.setString(6, idnum);
ps.setInt(7, amt);
ps.setString(8, datE);
ps.setString(9, actyp);
int count;
count = ps.executeUpdate();
count++;
count--;
//////////////////////////////
ReportPanel.userC.addItem(uid);
ViewAccount.userC.addItem(uid);
if (actyp.equals("Account User")) {
RechargePanel.userC.addItem(uid);
}
//////////////////////////////
JFrame msg1 = new JFrame();
JOptionPane.showMessageDialog(msg1, "An account has been successfully created", "Information", JOptionPane.INFORMATION_MESSAGE);
} else if (choice == JOptionPane.CANCEL_OPTION) {
JOptionPane.showMessageDialog(msg, "Account Creation Aborted", "Information", JOptionPane.INFORMATION_MESSAGE);
}
}
//conn.close();
} catch (SQLException e1) {
String error;
JFrame msg = new JFrame();
//error=e1.toString();
error = "Your entry for user id already exists";
JOptionPane.showMessageDialog(msg, error, "Error Message", JOptionPane.ERROR_MESSAGE);
} catch (Exception e1) {
// TODO Auto-generated catch block
String error;
JFrame msg = new JFrame();
error = e1.toString();
JOptionPane.showMessageDialog(msg, error, "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
///////////////////////////////////////////////////////////////////////////
if (str.equals("RESET")) {
try {
userFld.setText("");
nameFld.setText("");
pswrdFld.setText("");
addArea.setText("");
idFld.setText("");
} catch (Exception e2) {
String error;
JFrame msg = new JFrame();
error = e2.toString();
JOptionPane.showMessageDialog(msg, error, "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
}
///////////////////////////////////////////////////////////
public void keyPressed(KeyEvent key) {
//
}
/////////////////////////////////////////////////////
public void keyReleased(KeyEvent key) {
if (key.getSource() == pswrdFld) {
if (key.getKeyCode() == KeyEvent.VK_ENTER) {
}
}
}
/////////////////////////////////////////////////
public void keyTyped(KeyEvent key) {
//
}
//////////////////////////////////////////////
}
How to set all values to textbox?
field name data type
---------------------------------------------------------------------
Fld_First_Name varchar
Fld_Member_Id varchar
Fld_PAddr nvarchar
SELECT * FROM Members where Fld_Member_Id='14932';
_____________________________________________________________________________
Fld_Member_Id Fld_First_Name Fld_PAddr
______________________________________________________________________________
14932 abc abc
In WHERE clause of a SQL query a varchar variables should be within a single quotes. Try String s1 = "select * from Members where Fld_Member_Id='"+a+"'";
add Single quotes into the statement.And i think it should work setText method that you mentioned if you pass a varchar value correctly.
If you are not sure what is the type of memberID, then use
idFld.setText(String.valueOf("Your value"));
I need to create a program in which values can be inserted using textfield in Java.
database getting connected ...
bt Cannot insert values using JTextfield ....need help..
shows error ..
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
package youtubetest;
import java.sql.*;
import java.awt.event.*;
import javax.swing.*;
public class YouTubeTest extends JFrame{
private static final String USERNAME = "root";
private static final String PASSWORD = "****";
private static final String CONN_STRING = "jdbc:mysql://localhost:3306/youtube";
Connection conn;
PreparedStatement stmt;
JButton b1,b2;
JTextField t1,t2;
JLabel l1,l2;
String Fname;
String Lname;
public YouTubeTest()
{
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLayout(null);
add(t1 = new JTextField(30));
t1.setBounds(10,10,200,50);
add(t2 = new JTextField(30));
t2.setBounds(10, 100, 200, 50);
add(l1 = new JLabel("First Name : "));
l1.setBounds(220, 10, 200, 50);
add(l2 = new JLabel("Last Name : "));
l2.setBounds(220, 100, 200, 50);
add(b1 = new JButton("Submit"));
b1.setBounds(10, 400, 60, 60);
add(b2 = new JButton("Clear"));
b2.setBounds(100, 400, 60, 60);
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(CONN_STRING,USERNAME,PASSWORD);
System.out.println("Database Connected Succesfully ..... ");
stmt = conn.prepareStatement("Insert into user(Fname,Lname) values('"+Fname+"','"+Lname+"')");
}catch(Exception e){
e.printStackTrace();
}
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae){
try{
Fname = t1.getText();
Lname = t2.getText();
stmt.setString(1, Fname);
stmt.setString(2, Lname);
stmt.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
t1.setText("");
t2.setText("");
}
});
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
try{
stmt.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
});
setVisible(true);
}
public static void main(String[] args)throws Exception {
new YouTubeTest();
}
};
I wanted to authenticate a user.
For this I am using mysql connection.
The following is the code :
JTextField txt_Username= new JTextField();
String Username;
txt_Username.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent arg0) {
{
Username= txt_Username.getText();
}
});
Similarly there is code for password.
Now I want this username and password outside of its local scope so that clicking on the JButton will fire the sql databse and authenticate with the above username and password.
I am a naive in Java. Could anybody please help in here ?
I have the full code here . Please I need to understand where I am going wrong :
import java.awt.EventQueue;
public class Frame{
private private JFrame frame1;
private JTextField textFieldUserName;
private JTextField txtPassword;
public String textUserValue;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame window = new Frame();
window.frame1.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #throws SQLException
*/
public multipleFrame() throws SQLException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws SQLException
*/
private void initialize() throws SQLException {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setIcon(new ImageIcon("C:\\sad.jpg"));
lblNewLabel.setBounds(10, 36, 196, 187);
frame.getContentPane().add(lblNewLabel);
JLabel lbl_Password = new JLabel("PASSWORD");
lbl_Password.setBackground(new Color(128, 128, 128));
lbl_Password.setOpaque(true);
lbl_Password.setBounds(217, 140, 75, 14);
frame.getContentPane().add(lbl_Password);
final Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/schema","user","pwd");
final JTextField textFieldUserName = new JTextField();
textFieldUserName.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent arg0) {
String textUserValue = textFieldUserName.getText();
System.out.println(textUserValue+" hi");
String textUserValue1 =textUserValue;
}
});
System.out.println(textUserValue+" HI");
textFieldUserName.setBounds(324, 79, 108, 20);
frame.getContentPane().add(textFieldUserName);
textFieldUserName.setColumns(10);
System.out.println();
JLabel label = new JLabel("USERNAME");
label.setOpaque(true);
label.setBackground(Color.GRAY);
label.setBounds(216, 82, 75, 14);
frame.getContentPane().add(label);
txtPassword = new JTextField();
txtPassword.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent arg0) {
String textPasswordValue = txtPassword.getText();
System.out.println(textPasswordValue+" hi");
}
});
txtPassword.setColumns(10);
txtPassword.setBounds(324, 137, 108, 20);
frame.getContentPane().add(txtPassword);
JButton btnLogin = new JButton("LOGIN");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnLogin.setBounds(262, 200, 91, 23);
frame.getContentPane().add(btnLogin);
PreparedStatement stmt1 = null;
try {
stmt1 = con.prepareStatement("select username from LOGIN_TABLE where username='"+textUserValue+"'");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResultSet result1 = null;
try {
result1 = stmt1.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while (result1.next()) {
String user_name_db=result1.getString("username");
System.out.println(user_name_db);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Turn your Username variable into public. And place it just inside the class, not in any method.
Example:
public String Username;
Or if you want to retain its privacy you can create a .getMethod for it.
public String getUsername(){
return Username;
}
You can just create a model class with getters and setters:
class UserModel.java
public String Username;
public String getUserName()
{
return Username;
}
public void setUserName(String USER_NAME)
{
this.Username = USER_NAME;
}
In the main.java,
UserModel userObj = new UserModel();
txt_Username.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent arg0) {
{
userObj.setUserName(txt_Username.getText());
//Username= txt_Username.getText();
}
});
To retrieve it anywhere in main.java, use
String userName = userObj.getUserName();
I am creating a program that will take the data from several textboxes store in an array and when a next and previous button are pressed display the next or last position in the array, currently the next button gets stuck in a while loop without displaying and I'm not sure how to fix it, I am an amateur and I need help with this.
package major;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.List;
import java.awt.Label;
import javax.swing.JScrollPane;
import javax.swing.JList;
import javax.swing.JButton;
import javax.swing.JScrollBar;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
public class gui {
private JFrame frame;
private JTextField websitetxt;
private JTextField usernametxt;
private JTextField passwordtxt;
private encryptedData[] dataArray;
private int dataArrayMaxIndex;
private int dataArrayMax;
private int dataArrayCurrentIndex;
private JButton btnadd;
private JButton btnnew;
private JButton btndelete;
private JTextField notestxt;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
gui window = new gui();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public gui() {
initialize();
dataArrayMax = 20;
dataArray = new encryptedData[dataArrayMax];
dataArrayMaxIndex = 0;
while (dataArrayMaxIndex < dataArrayMax) {
dataArray[dataArrayMaxIndex] = new encryptedData();
dataArrayMaxIndex++;
}
dataArrayMaxIndex = -1;
dataArrayCurrentIndex = -1;
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 569, 427);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
websitetxt = new JTextField();
websitetxt.setBounds(315, 56, 191, 38);
frame.getContentPane().add(websitetxt);
websitetxt.setColumns(10);
usernametxt = new JTextField();
usernametxt.setColumns(10);
usernametxt.setBounds(315, 105, 191, 38);
frame.getContentPane().add(usernametxt);
passwordtxt = new JTextField();
passwordtxt.setColumns(10);
passwordtxt.setBounds(315, 154, 191, 38);
frame.getContentPane().add(passwordtxt);
JLabel lblWebsite = new JLabel("Website:");
lblWebsite.setBounds(227, 68, 78, 14);
frame.getContentPane().add(lblWebsite);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(227, 117, 78, 14);
frame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(227, 166, 78, 14);
frame.getContentPane().add(lblPassword);
final JButton btnadd = new JButton("Add to Database");
btnadd.setEnabled(false);
btnadd.setBounds(10, 105, 191, 38);
frame.getContentPane().add(btnadd);
JLabel lblPasswordManagerHsc = new JLabel("Password manager hsc 2014");
lblPasswordManagerHsc.setBounds(191, 11, 168, 14);
frame.getContentPane().add(lblPasswordManagerHsc);
final JButton btnnew = new JButton("New Record");
btnnew.setBounds(10, 56, 191, 38);
frame.getContentPane().add(btnnew);
JButton btndelete = new JButton("Delete Record");
btndelete.setBounds(10, 154, 191, 38);
frame.getContentPane().add(btndelete);
JButton btnprev = new JButton("Prev");
btnprev.setBounds(315, 316, 89, 23);
frame.getContentPane().add(btnprev);
JButton btnnext = new JButton("Next");
btnnext.setBounds(417, 316, 89, 23);
frame.getContentPane().add(btnnext);
notestxt = new JTextField();
notestxt.setBounds(315, 203, 191, 102);
frame.getContentPane().add(notestxt);
notestxt.setColumns(10);
JLabel lblnotes = new JLabel("Notes");
lblnotes.setBounds(227, 215, 46, 14);
frame.getContentPane().add(lblnotes);
JButton btngenerate = new JButton("Generate Password");
btngenerate.setBounds(10, 203, 191, 38);
frame.getContentPane().add(btngenerate);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu File = new JMenu("File");
menuBar.add(File);
JMenuItem save = new JMenuItem("Save");
File.add(save);
JMenuItem load = new JMenuItem("Load");
File.add(load);
JMenuItem mntmHelp = new JMenuItem("About");
File.add(mntmHelp);
websitetxt.setEnabled(false);
usernametxt.setEnabled(false);
passwordtxt.setEnabled(false);
notestxt.setEnabled(false);
btnadd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnadd.setEnabled(false);
dataArrayCurrentIndex++;
dataArrayMaxIndex++;
dataArray[dataArrayCurrentIndex].username = usernametxt.getText();
dataArray[dataArrayCurrentIndex].password = passwordtxt.getText();
dataArray[dataArrayCurrentIndex].notes = notestxt.getText();
dataArray[dataArrayCurrentIndex].website = websitetxt.getText();
}
});
btnnew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnnew) {
websitetxt.setEnabled(true);
usernametxt.setEnabled(true);
passwordtxt.setEnabled(true);
notestxt.setEnabled(true);
btnadd.setEnabled(true);
websitetxt.setText("");
usernametxt.setText("");
passwordtxt.setText("");
notestxt.setText("");
}
}
});
btndelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnprev.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnnext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = 0;
while (i < dataArrayMaxIndex) {
dataArrayCurrentIndex = i;
websitetxt.setText(dataArray[i].getWebsitename());
usernametxt.setText(dataArray[i].getUsername());
passwordtxt.setText(dataArray[i].getPassword());
notestxt.setText(dataArray[i].getNotes());
}
i++;
}
});
}
}
package major;
public class encryptedData {
public String website;
public String username;
public String password;
public String notes;
public encryptedData() {
try {
website = "";
username = "";
password = "";
notes = "";
} catch (Exception e) {
}
}
public encryptedData(String w, String u, String p, String n) {
try {
website = w;
username = u;
password = p;
notes = n;
} catch (Exception e) {
}
}
//Access methods
public String getWebsitename() {
return website;
}
public void setWebsiteName(String w) {
website = w;
}
public String getUsername() {
return username;
}
public void setUsername(String u) {
username = u;
}
public String getPassword() {
return password + "";
}
public void setPassword(String p) {
password = p;
}
public String getNotes() {
return notes + "";
}
public void setNotes(String n) {
notes = n;
}
}
You are incrementing i after the while loop in actionPerformed()!
If you had formatted your code better, this would have been obvious:
btnnext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = 0;
while (i<dataArrayMaxIndex) {
dataArrayCurrentIndex = i;
websitetxt.setText(dataArray[i].getWebsitename());
usernametxt.setText(dataArray[i].getUsername());
passwordtxt.setText(dataArray[i].getPassword());
notestxt.setText(dataArray[i].getNotes());
}
i++;
}
});
And this would have been even better:
btnnext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i<dataArrayMaxIndex; i++) {
dataArrayCurrentIndex = i;
websitetxt.setText(dataArray[i].getWebsitename());
usernametxt.setText(dataArray[i].getUsername());
passwordtxt.setText(dataArray[i].getPassword());
notestxt.setText(dataArray[i].getNotes());
}
}
});