I want to destroy the frame by clicking on a button. I searched everywhere and it seems that I'm doing this right. but it is not working.
public class LoginWindow {
public void CreateLoginWindow () {
/** Set Style to Main Frame **/
JFrame main_window = new JFrame();
main_window.setUndecorated(true);
main_window.setLocationRelativeTo(null);
main_window.setLayout(new BorderLayout());
main_window.setLayout(new FlowLayout());
main_window.setVisible(false);
main_window.setContentPane(new JLabel(new ImageIcon("images/MainWindow-bg.jpg")));
main_window.setExtendedState(JFrame.MAXIMIZED_BOTH);
main_window.setSize(1920,1080);
main_window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/** Some Codes **/
JButton login_button = new JButton("Click to Exit");
login_button.setBounds(920,480,120,45);
/** Login Button Action **/
login_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ValidateLogin validateLogin = new ValidateLogin();
Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText());
main_window.dispose();
}
});
main_window.add(login_button);
main_window.setVisible(true);
}
}
It seems ValidateLogin validateLogin = new ValidateLogin(); Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText()); make some problems.
And this is my ValidateLogin Class :
public class ValidateLogin {
public Boolean ValidateLoginAction (String username, String password){
ConnectToDB validate_login = new ConnectToDB();
String right_password = validate_login.GetPassOfAnUsername(username);
if ( right_password.equals(password) ){
return true;
} else {
return false;
}
}
}
And this is my ConnectToDB Class :
public class ConnectToDB {
/** Connect to Database **/
private Connection connect() {
String url = "jdbc:sqlite:E://Resturant Project/db/Resturant.db";
Connection connection = null;
try {
connection = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return connection;
}
/** Get Password of an Username **/
public String GetPassOfAnUsername(String username){
String password = "SELECT Password FROM Person WHERE UserName = '" + username +"'";
try (Connection connection = this.connect();
PreparedStatement statement= connection.prepareStatement(password);
ResultSet results = statement.executeQuery()) {
return results.getString("Password");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return null;
}
}
And this is my MainWindow Class :
public class MainWindow {
public static void main(String[] args) {
LoginWindow loginWindow = new LoginWindow();
loginWindow.CreateLoginWindow();
}
}
I have tried and I am able to close the window and jvm exits also. I provide below the button action code snippet.
login_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
ValidateLogin validateLogin = new ValidateLogin();
Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText());
}
catch(Exception ex) {
//handle exception
}
finally {
main_window.dispose();
}
}
});
Have the username_field and password_field variables been instantiated somewhere? Perhaps the line where you are accessing the getText() method is throwing a NullPointerException when the actionPerformed method is being called and so the program never reaches the main_window.dispose() line.
Try checking if both of those variables are null when the actionPerformed method is being executed before you try to access the getText() method from them.
On a further note, check if the connection the database is being established successfully.
ConnectToDB validate_login = new ConnectToDB();
String right_password = validate_login.GetPassOfAnUsername(username);
The second line might also throw a NullPointerException in case validate_login is null because your code will return null from your ConnectToDB() constructor in case the connection fails.
Related
I have been struggling with this problem for a while where I have two classes namely OrderSearch.java(main class) and CreateOrder.java. I have a JTable on my main class and when a row is doubleclicked it opens a new frame i.e CreateOrder.java with values from jTablein different textfields. I have a SaveButton in CreateOrder.java that saves the changes made in the class and shows it JTable again.
However the problem is I cannot perform refresh table operation i.e some sql queries when the SaveButton is clicked. I want the table in frame OrderSearch is refreshed when the savebutton on CreateOrder is clicked
Problems: Creating an object for class OrderSearch.java in CreateOrder.java gives me a stackoverflow error. Creating an object in the Savebutton opens a whole new frame again.
OrderSearch.java
public class OrderSearch extends CreateOrder{
//declarations for label,text, and buttons
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
OrderSearch window = new OrderSearch();
window.frmXraymanager.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public OrderSearch () { *Stack overflow error here*
initialize();
}
private void initialize() {
table = new JTable();
scrollPane.setViewportView(table);
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e2) {
if (e2.getClickCount() == 2 && !e2.isConsumed()) {
e2.consume();
try{
int index = table.getSelectedRow();
String table_Click = table.getModel().getValueAt(table.convertRowIndexToModel(index), 0).toString();
String sql = "SELECT ID, Date, Place, UserName FROM TEST.dbo.Intern WHERE ID = '"+table_Click+"'";
PreparedStatement pst = connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
if(rs.next()){
String id = rs.getString("ID");
String date = rs.getString("Date").toString();
String place = rs.getString("Place");
String uname = rs.getString("UserName");
frameCreate.setVisible(true); //Frame from CreateOrder.java
Number.setText(id); // textfields from CreateOrder.java
String date1 = startDate;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date date2 = df.parse(date1);
dateChooser.setDate(date2);
jobSite.setText(place);
uName.setText(uname);
Component.setText(component);
Remarks.setText(remarks);
rs.close();
pst.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
});
}
public void refresh()
{
query1 = "SELECT * FROM Test.dbo.Intern;
try(PreparedStatement pst = connection.prepareStatement(query1);
ResultSet rs = pst.executeQuery();){
table.setModel(DbUtils.resultSetToTableModel(rs));
table.setRowHeight(40);
}
catch(Exception e){
e.printStackTrace();
}
}
}
CreateOrder.java
public class CreateOrder {
public CreateOrder () {
initialize();
}
OrderSearch one = new OrderSearch(); *Stack overflow error here*
private void initialize() {
button_Save = new JButton("Save");
button_Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
*would like to add refresh() here*
}
});
}
}
How should I create an object of OrderSearch in CreateOrder to acces the method refresh() without opening the frame again?
Thanks in advance!
-Ajay
EDIT:
Actually the error is in
OrderSearch one = new OrderSearch();
and public OrderSearch () I totally understand it makes sense because it goes into infinite loop when I call an Object in CreateOrder.java. But is there any way to access the contents of OrderSearch.java in CreateOrder.java without getting the stackoverflow error or opening the whole new frame OrderSearch.java again?
No, there is no way to do it assuming your current setup. This leads us to the conclusion that you need to refactor the code. The main problem is that your code has no way to execute the required db command without creating a frame. You will need to separate the engine from the ui. You will need to be able to execute business logic without being tied to a UI event. The UI should be a user of the business logic, not its wrapper. You will need to move all your business logic into separate class(es) and call the relevant methods from the ui at the appropriate places and events.
I have created two swing.JFrames.
login GUI and user GUI. what I want is when it's switches to login gui to user gui, there is a Jlabel in user GUI which needs to be changed as ("you're logged in as" + username);
I tried this code in userjframe source code.
`loggedInAsLable.setText("you're logged in as" + username);`
in a method and it's called in main method of user jframe. but for some reasons
it doesn't work.
how can I run some methods when a Jframe is becoming visible?
public class CustomerServiceOfficerUI extends javax.swing.JFrame {
private static Statement st;
ResultSet rs;
Connection con = null;
Login loginUI = new Login(); // gets current user Id
Employee cso = new CustomerServiceOfficer(); //creates new customer service officer object
/**
* Creates new form CustomerServiceOfficer
*/
public CustomerServiceOfficerUI() {
initComponents();
}
public void getCSOdetails() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/flyingcarsdb", "root", "");
System.out.println("database connected");
} catch (ClassNotFoundException | SQLException ex) {
System.out.println("Error: " + ex);
}
try {
// Retrieve customer service officer details
st = con.createStatement();
String query = "select * FROM customerserviceofficer WHERE Id = '" + loginUI.getCurrentUserId() + "'";
rs = st.executeQuery(query);
while (rs.next()) {
//Assign the details with setters
cso.setFname(rs.getString("Fname"));
cso.setEmail(rs.getString("Email"));
}
} catch (Exception ex) {
System.out.println("Error : " + ex);
}
loggedInAsLable.setText("you're logged in as : " + cso.getId());
//this is where LABLE is changed, 'cso.getId()' returns the user ID
}
If you really need to update your JFrame when it becomes visible (as your last statement suggests), you can use the the WindowListener to call your getCSODetails() method.
public CustomerServiceOfficerUI() {
initComponents();
this.addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent e)
{
this.getCSODetails();
}
#Override
public void windowDeiconified(WindowEvent e)
{
this.getCSODetails();
}
#Override
public void windowActivated(WindowEvent e)
{
this.getCSODetails();
}
});
}
I've included three activation events - opening, activation and deiconfication; you can remove any of them to limit the update to a specific event suiting your needs. If you need to update the label only once the window is opened, remove the methods windowDeiconified() and windowActivated().
Note, however, that the getCSODetails() method is designed quite poorly and calling it whenever the window becomes visible/focused would incur a performance penalty and the responsiveness of your GUI will be heavily influenced by performance of your database. I guess that the customer details you're displaying are not changed during a login session, so it would be more appropriate to perform the query once, cache the details and then display them from the cache.
try this:
public class CustomerServiceOfficerUI extends javax.swing.JFrame {
private static Statement st;
ResultSet rs;
Connection con = null;
Login loginUI = new Login(); // gets current user Id
Employee cso = new CustomerServiceOfficer(); //creates new customer service officer object
/**
* Creates new form CustomerServiceOfficer
*/
public CustomerServiceOfficerUI() {
initComponents();
}
public void getCSOdetails() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/flyingcarsdb", "root", "");
System.out.println("database connected");
// Retrieve customer service officer details
st = con.createStatement();
String query = "select * FROM customerserviceofficer WHERE Id = '" + loginUI.getCurrentUserId() + "'";
rs = st.executeQuery(query);
while (rs.next()) {
//Assign the details with setters
cso.setFname(rs.getString("Fname"));
cso.setEmail(rs.getString("Email"));
}
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
loggedInAsLable.setText("you're logged in as : " + cso.getId());
loggedInAsLable.repaint();
}
});
} catch (Throwable ex) {
System.out.println("Error : " + ex);
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
loggedInAsLable.setText("There is a problem with your code : " + ex);
loggedInAsLable.repaint();
}
});
} finally {
}
//this is where LABLE is changed, 'cso.getId()' returns the user ID
}
I've written this code, but when run, it shows the error
sql command not properly ended
How can I fix it?
DatabasetableUI
public class DatabasetableUI extends UI {
#Override
protected void init(VaadinRequest request) {
DatabaseTableScreen screen = new DatabaseTableScreen();
try {
JDBCConnectionPool connectionPool = new SimpleJDBCConnectionPool( "oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:#usadc-sdbxt21:1521:GFRWMUAT","user", "password");
screen.populate("case_upload_history", connectionPool);
} catch (SQLException e) {
//System.out.println("Application");;
throw new RuntimeException( e.getMessage());
} enter code here
setContent( screen);
}
}
DatabaseTableScreen
public class DatabaseTableScreen extends VerticalLayout {private SQLContainer container;
private Table table;
public DatabaseTableScreen() {
setMargin( true);
table = new Table();
table.setPageLength( 10);
table.setEditable( true);
table.setSizeFull();
enter code here
//table.addGeneratedColumn("",new RemoveItemColumnGenerator());
addComponent(table);
}
public void populate( String tableName, JDBCConnectionPool connectionPool) {
QueryDelegate query = new TableQuery( tableName, connectionPool);
try {
container=new SQLContainer(query);
table.setContainerDataSource( container);
} catch (SQLException e) {
throw new RuntimeException( e);
}
}
}
Use the third argument to the TableQueryconstructor, like this:
QueryDelegate query = new TableQuery( tableName, connectionPool, new OracleGenerator());
This is my database connection class
import java.sql.*;
public class connectWithDB {
public static void DBconnection(){
Connection conn = null;
String url = "jdbc:derby://localhost:1527/";
String dbName = "MyTinyShopDB";
String driver = "org.apache.derby.jdbc.ClientDriver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
//conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
This is code for login button
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
PreparedStatement prestmnt = null;
ResultSet Reltset = null;
try {
String sql = "SELECT * FROM LOGINDETAILS WHERE LOGINID='"+txtFieldUserName.getText()+"'AND USERPASSWORD='"+txtFieldPassword.getText()+"'";
prestmnt=conn.prepareStatement(sql);
Reltset=prestmnt.executeQuery();
if (Reltset.next()){
AdminMainForm adminform = new AdminMainForm();
adminform.setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null, "User Name or Password is Wrong");
}
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
Program is running but when i click the login button these errors appears in netbeans
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at mytinyshop.Login.btnLoginActionPerformed(Login.java:159)
at mytinyshop.Login.access$200(Login.java:18)
at mytinyshop.Login$3.actionPerformed(Login.java:77)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341 )
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java: 402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
and more errors
i have added user name and password in database it has to check the database if the username and passsword are correct it has to goto the other form otherwise it has to show wrong password dialog please someone help me..
You set your connection to null at the start of btnLoginActionPerformed()
Connection conn = null;
And then you try and use it 5 lines later
prestmnt=conn.prepareStatement(sql);
Calling a method on null reference will cause a NullPointerException
Java exceptions are generally very good at telling you what is wrong and where. You have a NullPointerException in the btnLoginActionPerformed method; it tells you the exact line, though we cannot tell from what you've posted. The prestmnt could be null (error in the SQL), or there could be an error in the query so that you're getting null results so Reltset is null. Debug it.
import java.swing.*;
import java.sql.*;
Connection c=null;
PreparedStatement pst = null;
ResultSet r=null;
String s;
try
{
c=DriverManager.getConnection("jdbc:derby://localhost:1527/users","rishi","123");
s="SELECT * FROM RISHI.USERDETAILS WHERE name='"+txt_name.getText()+"' AND password='"+txt_pass.getText()+"'";
pst=c.prepareStatement(s);
r=pst.executeQuery();
if(!txt_name.getText().trim().isEmpty())
{
if(!txt_pass.getText().trim().isEmpty())
{
if(r.next())
{
JOptionPane.showMessageDialog(this,"Welcome");
}
else
{
JOptionPane.showMessageDialog(this,"Username or password is wrong");
}
}
else
{
JOptionPane.showMessageDialog(this,"Enter The password");
}
}
else
{
JOptionPane.showMessageDialog(this,"Enter The Username");
}
}
catch(Exception n)
{
JOptionPane.showMessageDialog(null,n.getMessage());
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new login().setVisible(true);
}
});
}
}
Connection c=null;
PreparedStatement pst=null;
ResultSet r=null;
String s;
try
{
c=DriverManager.getConnection("jdbc:derby://localhost:1527/users","rishi","123");
s="SELECT * FROM RISHI.USERDETAILS WHERE name='"+txt_name.getText()+"' AND password='"+txt_pass.getText()+"'";
pst=c.prepareStatement(s);
r=pst.executeQuery();
if(!txt_name.getText().trim().isEmpty())
{
if(!txt_pass.getText().trim().isEmpty())
{
if(r.next())
{
JOptionPane.showMessageDialog(this,"Welcome");
}
else
{
JOptionPane.showMessageDialog(this,"Username or password is wrong");
}
}
else
{
JOptionPane.showMessageDialog(this,"Enter The password");
}
}
else
{
JOptionPane.showMessageDialog(this,"Enter The Username");
}
}
catch(Exception n)
{
JOptionPane.showMessageDialog(null,n.getMessage());
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new login().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton b;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField txt_name;
private javax.swing.JTextField txt_pass;
// End of variables declaration
}
I have a main frame that has a list and "add" button. When I click on the 'add' button, one frame will be shown that I can enter name, family and id.
And by clicking on the "addAPerson", the name will be stored in the SQL. But when I close the frame, the new person will not be added to my list which is in my main frame but if I close the main frame and run it again, the new person will be added to the list.
How can I update the JList without running the main frame?
My main frame (a part of that):
public class ListFrame extends javax.swing.JFrame {
private InformationClass client;
private DefaultListModel model = new DefaultListModel();
/** Creates new form ListFrame. */
public ListFrame(InformationClass client) {
initComponents();
this.client = client;
fillTable();
}
public void fillTable() {
try {
List<InformationClass> list = null;
list = Manager.getClientListFromMySQL();
if (list == null) {
JOptionPane.showMessageDialog(
this,
"You should add a person to your list",
"Information",
JOptionPane.OK_OPTION);
return;
}
else {
for (int i = 0; i < list.size(); i++) {
InformationClass list1 = list.get(i);
model.add(i, list1.getId());
}
jList1.setModel(model);
}
}
catch (SQLException ex) {
Logger.getLogger(
ListFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
My frame which will be shown when you click on the add button (a part of that):
public class Add extends javax.swing.JFrame {
private InformationClass client;
public Add(InformationClass client) {
initComponents();
this.client = client;
}
private void addAPersonActionPerformed(java.awt.event.ActionEvent evt) {
submit();
clear();
}
private void submit() {
String s1 = nameF.getText();
String s2 = familyF.getText();
String s3 = iDf.getText();
if (s1.equals("") || s2.equals("") || s3.equals("")) {
JOptionPane.showMessageDialog(
this,
"fill the empty name/family/id text fields",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else {
try {
boolean b = Manager.isAddPerson(s1, s2, s3);
if (b == false) {
Manager.addPerson(s1, s2, s3);
JOptionPane.showMessageDialog(
this,
"The person has been added successfully",
"Information",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(
this,
"These datas has been added before!!",
"Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
catch (NullPointerException e) {
e.printStackTrace();
}
}
}
}
My Manager class (a part of that):
public static void addPerson(String name, String family, String yahooId) {
PreparedStatement pstmt;
String query;
try {
query = ("INSERT INTO newpersontable(name,family,yahooId) VALUES(?,?,?)");
pstmt = (PreparedStatement) conn.prepareStatement(query);
pstmt.setString(1, name);
pstmt.setString(2, family);
pstmt.setString(3, yahooId);
pstmt.executeUpdate();
}
catch (SQLException e) {
Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, e);
}
}
An implementation of the Observer pattern will do the trick.
Your InformationClass calls the Manager to add a person, if it is not already known. But you want that new person appear in the ListFrame. With the Observer pattern, the ListFrame will observe the Manager if it has some added, changed or deleted records. If it is the case, the ListFrame can update itself with the actual values, that it just requests again from the Manager.
We need one additional interface, a Listener and some methods on the Manager, that's all.
Here's a basic implementation:
public interface PersonsModelChangeListener {
public void modelHasChanged();
}
In Manager, add the following fields and methods:
List<PersonsModelChangeListener> listeners = new ArrayList<PersonsModelChangeListener>();
public void addListener(PersonsModelChangeListener listener) {
listeners.add(listener);
}
private void fireModelChangeEvent() {
for (PersonsModelChangeListener listener:listeners) {
listener.modelHasChanged();
}
}
Add the following line to the add method of Manager:
public void add(String s1, String s2, String s3) {
// existing code
fireModelChanged();
}
Next step: make ListFrame implement the PersonsModelChangeListener interface and implement the modelHasChanged method so that ListFrame can 'get' the actual values whenever the Managers data set has changed.
Edit
public class Manager {
// existing code
private static List<PersonsModelChangeListener> listeners = new ArrayList<PersonsModelChangeListener>();
public static void addListener(PersonsModelChangeListener listener) {
listeners.add(listener);
}
private static void fireModelChangeEvent() {
for (PersonsModelChangeListener listener:listeners) {
listener.modelHasChanged();
}
}
public static void addPerson(String name, String family, String yahooId) {
PreparedStatement pstmt;
String query;
try {
query = ("INSERT INTO newpersontable(name,family,yahooId) VALUES(?,?,?)");
pstmt = (PreparedStatement) conn.prepareStatement(query);
pstmt.setString(1, name);
pstmt.setString(2, family);
pstmt.setString(3, yahooId);
pstmt.executeUpdate();
fireModelChangedEvent();
} catch (SQLException e) {
Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, e);
}
}
public class ListFrame extends javax.swing.JFrame implements PersonsModelChangeListener {
// your fields
/** Creates new form ListFrame */
public ListFrame(InformationClass client) {
initComponents();
this.client = client;
fillTable();
Manager.addListener(this);
}
#Override
public void modelHasChanged() {
// this method will be called when you add something with the
// Manager.
// Add your code here to get the actual data from the Manager
// and update this component
}
}
Hope it helps :)
In the submit method save the created person and create a field for it which you can 'get' from the actionPerformed method for the 'add' button in the ListFrame class. Then just add it to the list model.
you just call the update method at the end of your coding.the update method should display the table.So when you add some thing to the list it will get updated in the database. so at the end of your coding it will call the update method which will display the updated table.Hopu u got my point