将JFrame与变量连接

时间:2014-01-19 15:14:57

标签: java mysql swing

我有一个用于登录表单的程序。我试图在actionListener方法中获取本地的用户变量,以便在用户回答问题时在mysql数据库中使用它。所以基本上我有这个类,用户进行他的登录,然后它转到另一个表单点击开始测试,然后它转到我想要使用用户变量的表单。我已经完成了getter和setter方法以获得用户名,然后在用户回答问题的JFrame中使用它。当我在这个类中打印一条消息时,它返回用户变量。但是当我想在其他JFrame中使用它时,它返回null!任何想法,我该怎么做?

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;
          }


}

另一堂课:

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);

    }
}

编辑(20/1):新的登录表单(用户变量所在的sql部分)

      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);
            }

        }
    });

1 个答案:

答案 0 :(得分:1)

建议:

  • 您的登录窗口不应该是JFrame,而应该是模式对话框,例如JOptionPane或模态JDialog。这样,当您的调用代码显示对话框时,调用代码中的所有代码流都会停止,并在对话框不再可见之前保持暂停状态。
  • 一旦对话框不再可见并且调用代码恢复,则可以查询对话框类的状态并获取登录信息。
  • 您没有向我们展示(或者我没有看到)您是如何尝试从其他地方调用此代码的。这是关键,因为这是您的问题所在,也是我们必须看到的。
  • 正如kleopatra所说,不要使用空布局和直接定位以及组件的大小调整它会让你感到高兴,相信我。

修改

是的,我相信您的问题与我预测的一样,是因为您正在使用JFrame作为对话框窗口。看这里:

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

由于Build1是一个非模态JFrame,因此当它设置为可见时,它不会阻止调用代码。因此,在用户有机会将数据输入Build1窗口之前,会立即调用a.getUsername()

一种解决方案是使用WindowListener来查看Build1窗口何时不再可见,但为什么要经历这个混乱。相反,为什么不简单地使用模态 JDialog而不是对话窗口的JFrame。


同样,你会想要停止使用空布局和绝对定位,相信我。它会咬你。


编辑2
你说:

  

首先,你能给我一个JDialog的例子吗?

创建和使用JDialog类似于创建JFrame,除了你应该在构造函数中传递对父窗口的引用,并告诉它是模态的。请查看JDialog API以了解其构造函数的具体信息。另外,我在这个网站上写了许多使用它的例子,我邀请你在我的名字和术语JDialog上搜索这个网站,你会发现我写的很多例子。另外,我建议您将大部分GUI创作用于创建JPanels,然后您可以轻松地将这些JPanel放置在需要的地方:JFrame,模态JDialog,JOptionPane,另一个JPanel,......等等。它给你的GUI具有很大的灵活性。

  

第二个空布局就是这个意思:contentPane.setLayout(null); ?

  

为什么我必须停止使用它们?我的代码会出问题吗?

您的GUI将非常“僵硬”,虽然它可能在您的系统上看起来不错,但在其他平台甚至类似平台上可能看起来不太好但屏幕分辨率不同。不仅你的GUI很难改变,更新或改进。例如,请查看我的StackOverflow答案here中的代码。该代码创建了一个JPanel,它使用GridBagLayout显示JLabel和JTextFields的网格,并显示如下:

enter image description here

在该代码中,我使用简单的String数组指定JLabel:

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

正如我在答案中所述,这段代码的美妙之处在于,如果你想添加另一个字段,比如一个线条粗细字段,并想要添加它以使其倒数第二,那么唯一需要改变的是代码是改变这个:

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

到此:

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

结果是:

enter image description here

这是唯一可行的,因为我使用布局管理器来帮助我生成GUI。如果您手动执行此操作,则必须定位新组件,但是,您必须手动重新定位添加的任何新组件下方和右侧的所有组件。如果对GUI进行重大更改,这可能很麻烦并且非常容易出错。相反,布局管理人员将为您完成所有繁重的工作。

另请注意,此代码是使用GUI创建JPanel的示例,我在JOptionPane中显示这是一种模式对话框的形式,这实际上可以很好地为您服务。