1

I have this program that is for a login form. I am trying to take user variable that is local in the actionListener method in order to use it in mysql database when the user answer a question. So basically I have this class that the user does his login and then it goes to another form to click to begin the test and then it goes to the form that I want to use user variable. I have done getter and setter methods in order to have username and then use it in the JFrame which user answers a question. When I print a message in this class, it returns user variable. But when I want to use it in the other JFrame it returns null! Any ideas, how can I do it?

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.swing.JPasswordField;


public class Build1 extends JFrame  {

    private JPanel contentPane;
    private JTextField textField;
    private JPasswordField passwordField;
    private String user;
    JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Build1 frame = new Build1();
                    frame.setVisible(true);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Build1() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 500, 500);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textField = new JTextField();
        textField.setBounds(96, 58, 86, 20);
        contentPane.add(textField);
        textField.setColumns(10);


        JLabel lblUsername = new JLabel("Username");
        lblUsername.setBounds(10, 61, 59, 14);
        contentPane.add(lblUsername);

        JLabel lblPassword = new JLabel("Password");
        lblPassword.setBounds(10, 113, 59, 14);
        contentPane.add(lblPassword);

        JButton btnLogin = new JButton("Login");
        btnLogin.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e)
            {
                try{
                String user = textField.getText().trim();
                String pass = String.valueOf(passwordField.getPassword());
                setUsername(user);
                getUsername();

                Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users","root","1234");
                PreparedStatement st = con.prepareStatement("select * from user where username='"+user+"'");
                ResultSet rs = st.executeQuery();

                if(rs.next())
                {

                    String dbpass = rs.getString(4);

                    if(dbpass.equals(pass)){                    
                        if(user.equals("Admin")){               
                            Build5 Admin = new Build5();
                            Admin.setVisible(true);             
                            Build1.this.dispose();
                            Build1.this.setVisible(false);
                        }
                        else{   
                            JOptionPane.showMessageDialog(frame," "+user);
                            Build2 User = new Build2();
                            User.setVisible(true);
                            Build1.this.dispose();
                            Build1.this.setVisible(false);
                        }
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(null,"Login Unsuccessful!","Error",1);
                    }

                }
                else
                {
                    JOptionPane.showMessageDialog(null,"Username not found","Error",1);
                }

            } catch (SQLException ex) {
                System.out.println(ex);
            }

        }
    });
        btnLogin.setBounds(186, 202, 89, 23);
        contentPane.add(btnLogin);

        JButton btnRegister = new JButton("Register");
        btnRegister.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e){
            try {
                    Build3 frame = new Build3();
                    frame.setVisible(true);
                    Build1.this.dispose();
                    Build1.this.setVisible(false);

                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        });
        btnRegister.setBounds(186, 236, 89, 23);
        contentPane.add(btnRegister);

        JButton btnRecoverPassword = new JButton("Recover Password");
        btnRecoverPassword.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e){
            try {
                    Build4 frame = new Build4();
                    frame.setVisible(true);
                    Build1.this.dispose();
                    Build1.this.setVisible(false);

                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        });
        btnRecoverPassword.setBounds(153, 270, 147, 23);
        contentPane.add(btnRecoverPassword);

        passwordField = new JPasswordField();
        passwordField.setBounds(96, 110, 86, 20);
        contentPane.add(passwordField);



    }

    public void setUsername(String user){
        this.user = this.textField.getText();
    }

      public String getUsername() {
          JOptionPane.showMessageDialog(frame,"1 "+user);
          return user;
          }


}

The other class:

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JLabel;


public class Build6 extends JFrame {

    private JPanel contentPane;
     JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Build6 frame1 = new Build6();
                    frame1.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }



        });
    }

    /**
     * Create the frame.
     */
    public Build6() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 500, 500);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        final JRadioButton rdbtnTrue = new JRadioButton("True");
        rdbtnTrue.setBounds(162, 132, 109, 23);
        contentPane.add(rdbtnTrue);

        final JRadioButton rdbtnFalse = new JRadioButton("False");
        rdbtnFalse.setBounds(162, 158, 109, 23);
        contentPane.add(rdbtnFalse);

        final JRadioButton rdbtnDontKnow = new JRadioButton("Don't know");
        rdbtnDontKnow.setBounds(162, 184, 109, 23);
        contentPane.add(rdbtnDontKnow);

        final JRadioButton rdbtnWhatever = new JRadioButton("Whatever");
        rdbtnWhatever.setBounds(162, 210, 109, 23);
        contentPane.add(rdbtnWhatever);

        JLabel lblDoesAMan = new JLabel("Does a man fly?");
        lblDoesAMan.setBounds(162, 97, 109, 14);
        contentPane.add(lblDoesAMan);

        JButton btnAnswer = new JButton("Answer");
        btnAnswer.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
        try {
              Build1 a = new Build1();
              String user = a.getUsername();

            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/answers","root","1234"); 
            Connection con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/users","root","1234");
            PreparedStatement st = con1.prepareStatement("select * from user where username='"+user+"'");

            ResultSet rs = st.executeQuery();
            while(rs.next()){
                 String username = rs.getString("username");


            if(user.equals(username)){

                JOptionPane.showMessageDialog(frame,"DAN DAN!"+user+" "+username);


            }
            }

            if(rdbtnDontKnow.isSelected()){

                java.util.Date dt = new java.util.Date();

                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                java.text.SimpleDateFormat sdf1 = new java.text.SimpleDateFormat("yyyy-MM-dd");

                String currentday = sdf1.format(dt);
                String currentdayTime = sdf.format(dt);

                String answer = "Wrong";
                String test ="test1";

                PreparedStatement st11 = (PreparedStatement) con.prepareStatement("INSERT INTO answer (username,daytime,answer,test,day) VALUES (?,?,?,?,?)");
                st11.setString(1, user);
                st11.setString(2, currentdayTime);
                st11.setString(3, answer);
                st11.setString(4, test);
                st11.setString(5, currentday);
                st11.executeUpdate();
                st11.close();

                }
            else if(rdbtnWhatever.isSelected()){

                java.util.Date dt = new java.util.Date();

                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                java.text.SimpleDateFormat sdf1 = new java.text.SimpleDateFormat("yyyy-MM-dd");
                String currentdayTime = sdf.format(dt);
                String currentday = sdf1.format(dt);

                String answer = "Wrong";
                String test ="test1";

                PreparedStatement st11 = (PreparedStatement) con.prepareStatement("INSERT INTO answer (username,daytime,answer,test,day) VALUES (?,?,?,?,?)");
                st11.setString(1, user);
                st11.setString(2, currentdayTime);
                st11.setString(3, answer);
                st11.setString(4, test);
                st11.setString(5, currentday);
                st11.executeUpdate();
                st11.close();
            }
            else if(rdbtnTrue.isSelected()){

                java.util.Date dt = new java.util.Date();

                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                java.text.SimpleDateFormat sdf1 = new java.text.SimpleDateFormat("yyyy-MM-dd");

                String currentday = sdf1.format(dt);
                String currentdayTime = sdf.format(dt);

                String answer = "Wrong";
                String test ="test1";

                PreparedStatement st11 = (PreparedStatement) con.prepareStatement("INSERT INTO answer (username,daytime,answer,test,day) VALUES (?,?,?,?,?)");
                st11.setString(1, user);
                st11.setString(2, currentdayTime);
                st11.setString(3, answer);
                st11.setString(4, test);
                st11.setString(5, currentday);
                st11.executeUpdate();
                st11.close();
            }
            else if(rdbtnFalse.isSelected()){

                java.util.Date dt = new java.util.Date();

                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                java.text.SimpleDateFormat sdf1 = new java.text.SimpleDateFormat("yyyy-MM-dd");

                String currentday = sdf1.format(dt);
                String currentdayTime = sdf.format(dt);

                String answer = "Wrong";
                String test ="test1";

                PreparedStatement st11 = (PreparedStatement) con.prepareStatement("INSERT INTO answer (username,daytime,answer,test,day) VALUES (?,?,?,?,?)");
                st11.setString(1, user);
                st11.setString(2, currentdayTime);
                st11.setString(3, answer);
                st11.setString(4, test);
                st11.setString(5, currentday);
                st11.executeUpdate();
                st11.close();

            }else{
                JOptionPane.showMessageDialog(frame,"Select an answer!");
            }

            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
        btnAnswer.setBounds(192, 261, 89, 23);
        contentPane.add(btnAnswer);

        ButtonGroup group = new ButtonGroup(); //Σε περίπτωση που θέλουμε να διαλέγει μόνο ένα!
        group.add(rdbtnTrue);
        group.add(rdbtnFalse);
        group.add(rdbtnDontKnow);
        group.add(rdbtnWhatever);

    }
}

Edit(20/1): The new Login Form (sql part where user variable is located)

      JButton lgnBtn = new JButton("Login");
      lgnBtn.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e)
            {
                try{
                String user = t.getText().trim();


                String pass = String.valueOf(t1.getPassword());

                Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users","root","1234");
                PreparedStatement st = con.prepareStatement("select * from user where username='"+user+"'");
                ResultSet rs = st.executeQuery();

                if(rs.next())
                {

                    String dbpass = rs.getString(4);

                    if(dbpass.equals(pass)){                    
                        if(user.equals("Admin")){               
                            Build5 Admin = new Build5();
                            Admin.setVisible(true);             
                        }
                        else{   

                            JOptionPane.showMessageDialog(frame," "+user);
                            Build2 User = new Build2();
                            User.setVisible(true);
                        }
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(null,"Login Unsuccessful!","Error",1);
                    }

                }
                else
                {
                    JOptionPane.showMessageDialog(null,"Username not found","Error",1);
                }

            } catch (SQLException ex) {
                System.out.println(ex);
            }

        }
    });
pap
  • 283
  • 1
  • 7
  • 18
  • unrelated: don't do any manual sizing/locating of components, ever - that's the exclusive responsibility of the LayoutManager. – kleopatra Jan 19 '14 at 15:19

1 Answers1

1

Suggestions:

  • Your log-in window should not be a JFrame, but instead should be a modal dialog such as either a JOptionPane or a modal JDialog. This way, when your calling code displays the dialog, all code flow in the calling code stops, and remains halted until the dialog is no longer visible.
  • Once the dialog is no longer visible and the calling code resumes, this when you can query the dialog class's state and get the log-in information.
  • You don't show us (or I'm not seeing) how you try to call this code from elsewhere. This is key since that is where your problem is located, and which is what we must see.
  • As kleopatra states, don't use null layout and direct positioning and sizing of components for it will come back to bite you in the tush, trust me.

Edit

Yep, I believe that your problem is as I predicted and is because you're using a JFrame as a dialog window. Look here:

Build1 a = new Build1();  
String user = a.getUsername();

Since Build1 is a non-modal JFrame, it does not block the calling code when it is set visible. And so a.getUsername() is called immediately before the user has had a chance to enter data into the Build1 window.

One solution is to use a WindowListener to see when the Build1 window is no longer visible, but why go through that mess. Instead why not simply use a modal JDialog not a JFrame for your dialog window.


Again, you will want to stop using null layouts and absolute positioning, trust me. It will bite you.


Edit 2
You state:

First, can you give me an example of JDialog?

Creating and using a JDialog is similar to creating a JFrame except that you should pass in a reference to the parent window in the constructor as well as tell it to be modal or not. Please have a look at the JDialog API for specifics on its constructor. Also, I've written many examples of using this on this site, and I invite you to please have a search of this site on my name and the term JDialog and you'll find plenty of examples that I've written. Also, I suggest that you gear most of your GUI creations towards the creation of JPanels, and then you can easily place those JPanels where needed: a JFrame, a modal JDialog, a JOptionPane, another JPanel,... etc. It gives your GUI's a lot of flexibility.

And second null layouts you mean this: contentPane.setLayout(null); ?

Yes.

Why do I have to stop using them? Will be a problem with my code?

Your GUI will be very "rigid", and while it might look OK on your system, will likely not look good on other platforms or even on similar platforms but with different screen resolution. Not only that your GUI's will be very hard to change, update, or improve. For example, please have a look at my code in my StackOverflow answer here. The code creates a JPanel that shows a grid of JLabels and JTextFields using a GridBagLayout and displays like so:

enter image description here

In that code, I specify the JLabels with a simple String array:

String[] labelTexts = new String[] { "Width of Frame:",
    "Height of Frame:", "# OF Balls:", "Color:" };

As I state in the answer, the beauty of this code, is if you wish to add another field, say a line thickness field, and want to add it so that it is second to last, then the only change needed to the code would be to change this:

  String[] labelTexts = new String[] { "Width of Frame:",
        "Height of Frame:", "# OF Balls:", "Color:" };

to this:

  String[] labelTexts = new String[] { "Width of Frame:",
        "Height of Frame:", "# OF Balls:", "Line Thickness:", "Color:" };

Which results in:

enter image description here

This is only possible since I used layout managers to help me generate the GUI. If you did this by hand, you'd have to position the new component, but also, you'd have to manually reposition all components below and to the right of any new components added. If you make significant changes to the GUI, this can be cumbersome and very error prone. The layout managers here instead will do all the heavy lifting for you.

Note also that this code is an example of using a GUI to create a JPanel which I display in a JOptionPane, a form of a modal dialog, and that this in fact could work well for you.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • First, can you give me an example of JDialog? And second null layouts you mean this: contentPane.setLayout(null); ? Why do I have to stop using them? Will be a problem with my code? – pap Jan 19 '14 at 16:20
  • Yes I am here! I am trying to do what you said,but I got myself into a lot of trouble with JDialog. Now I am trying with JOptionPane, but I cannot find a way to put JButton and not have the default options such as Y/N, Y/N/C etc. – pap Jan 19 '14 at 19:23
  • @pap: then best to go the route of a JDialog. Again, focus your attention towards creating JPanels, and don't extend JFrame or JDialog. Then when the dialog is needed, create it in vivo, add your JPanel to its contentPane, and launch it. – Hovercraft Full Of Eels Jan 19 '14 at 19:46
  • What does it mean "create it in vivo"? Okay, I will stick to that (JPanel) and build it as you say without absolute positioning. – pap Jan 19 '14 at 19:53
  • This is a scientific term. "in vivo" means "within the living" as opposed to "in vitro" which is in the petri dish. What I mean is to create the JDialog while the program is running only when needed. – Hovercraft Full Of Eels Jan 19 '14 at 20:00
  • Okay so I created different JPanels as you said and had inside them JFrames (not JDialogs). I found and your post: http://stackoverflow.com/questions/13907202/adding-components-into-jpanel-inside-a-jframe?answertab=votes#tab-top So now I have a question. How can I dispose the JPanel? because it wouldn't let me do the same as JFrames (method.this.dispose(). – pap Jan 19 '14 at 22:26
  • @pap: you don't -- you dispose its containing Window the JDialog. This can be obtained from within the JPanel via the `SwingUtilities.getAncestorWindow(...)` method. – Hovercraft Full Of Eels Jan 19 '14 at 22:29
  • Okay. Now to the basic problem, I want now to access to the variable user (I updated my answer!). How am I going to do that? – pap Jan 19 '14 at 22:34
  • @pap: Gosh there's so much unnecessary code in your post, as well as unmet dependencies (classes that are declared but not available to us). It would be so much easier if you created and posted a [Minimal, Complete, Tested and Readable example](http://stackoverflow.com/help/mcve), I made one out of your last post, but am running out of time to do that now. – Hovercraft Full Of Eels Jan 19 '14 at 22:38
  • Indeed. But I believe, after 8 hours straight of programming, I have so much on my head, that's why I didn't do what you asked. Thank you very much for your time, I appreciate it. – pap Jan 19 '14 at 22:42
  • @pap: you're welcome. If you do get the time and inclination to create and post your minimal example (without database stuff, with only code needed to show your problem), please feel free to post it and notify me in comment. I'm signing out for now. Good luck. – Hovercraft Full Of Eels Jan 19 '14 at 22:44
  • The problem is in the sql part, because this is where is located user variable! I updated the code! – pap Jan 20 '14 at 00:42
  • I may found a solution! (it worked to be more specific) I changed user variable to a public static and then called a getter method to return it and use it to another class. It worked and not only in JPanel that I build after, but also in the first gui that I built with absolute positioning and JFrames. Now I don't which one to choose! (but I think your opinion about absolute positioning and JFrames, are good so I will stick to your solution!) – pap Jan 20 '14 at 01:09
  • @pap: Make it a field, but not a static field, no, that is bad coding practice and suggests a design flaw. – Hovercraft Full Of Eels Jan 20 '14 at 01:26
  • When I leave it as a field it always gives me the same mistake: Cannot make a static reference to the non-static method ... from the type ... Since I want to be static this variable for everytime that someone does a login what is the problem? If you have any suggestion on how to get passed from this problem with another way, please tell me more!I will be glad to hear it. – pap Jan 20 '14 at 01:43
  • Sorry, but that is so wrong, and you're fixing the wrong thing. The solution is to call the public methods off of an instance, an object. You need to read up on OOP first principles because your statements above suggest that this will help you code better. I strongly urge you to put aside GUI programming for a bit and read Bruce Eckel's [Thinking in Java](http://www.mindview.net/Books/TIJ/). – Hovercraft Full Of Eels Jan 20 '14 at 02:08
  • I will read it because I think the same thing (about OOP firt principles), about GUI programming I will keep going and read together. In any case thanks for your time. – pap Jan 20 '14 at 02:14