我的程序的动作监听器无法工作[英] My program's Action Listener won't work

本文是小编为大家收集整理的关于我的程序的动作监听器无法工作的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

又是我,我似乎无法使此代码工作.我基本上要问有关该按钮在单击时什么都不执行的任何建议.您要我附加源代码吗?

我正在尝试实现的方法:

   public static void UserInput() {
      try {
         stmt = connect.createStatement();
         ResultSet res = stmt.executeQuery("SELECT * FROM " + tableName);
         while (res.next()) {
            if (res.getString("Username").equals(usernameField.getText())) {
               if (res.getString("Password").equals(passwordField.getPassword())) {
                  JOptionPane.showMessageDialog(null, "Correct", "Correct",
                           JOptionPane.INFORMATION_MESSAGE);
               } else {
                  JOptionPane.showMessageDialog(null, "Error. Incorrect "
                           + "username or password.", "Error",
                           JOptionPane.ERROR_MESSAGE);
               }
            } else {
               JOptionPane.showMessageDialog(null, "Error. Incorrect "
                        + "username or password.", "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
         }
         res.close();
         stmt.close();
         connect.close();

      } catch (SQLException sqlExcept) {
         sqlExcept.printStackTrace();
      }

   }

这就是我称之为:

             if(firstTime == false) {
              JavaDB jdb = new JavaDB();
         }

        JavaDB window = new JavaDB("");
        window.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                    System.exit(0);
                }
            });
        }

这是ActionListner:

            submit = new JButton("Submit");
            c.add(submit);
              submit.addActionListener( new ActionListener() {  
                    public void actionPerformed( ActionEvent e ) { 
                      if(e.getSource().equals(submit)) {
                         UserInput();
            }
         }  
     });  ;        

如果您需要的话,请告诉我.我一直在自学爪哇,但我真的不知道该学习什么,所以会欢迎任何技巧.我也是堆栈溢出和发布代码的新手,因此您可以给我的任何东西都将受到欣赏.预先感谢.

编辑:我现在添加了一个用于事件处理的课程,其中包括这样的线程;

             public class ButtonHandler implements ActionListener{
    public void actionPerformed(ActionEvent e){
        if(e.getSource().equals(submit)){
            Thread th = new Thread(new JavaDB());
            th.start();
            th.run();
            try {
                th.wait();
            } catch (InterruptedException e1) {
            }
        }
        else{
        System.exit(0);
        }   
    }

我将用户input更改为run().但是,现在,当我单击"提交"按钮时,GUI消失了.仅供参考,这是我的主要方法:

             public static void main(String args[]) throws SQLException,
        InterruptedException {
    createConnection();
    boolean firstTime = firstTime();
    if (firstTime) {
        JavaDB db = new JavaDB("");
        db.createAccount();
        try {
            connect = DriverManager
                    .getConnection("jdbc:derby:\\KeithDB;shutdown=true");
        } catch (SQLException XJ015) {
        }
    }
    if (firstTime == false) {
        JavaDB jdb = new JavaDB();
        Thread th = new Thread();
    }

    JavaDB window = new JavaDB("");
    window.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
}

您需要的其他任何东西,让我知道

推荐答案

如何使用密码字段/em> ,对于您的学习来说将是一个很好的起点,它将有效 sscce .

附录:没有一个完整的示例或了解您使用的数据库的知识,我得到了以下结果,

Version: H2 1.3.157 (2011-06-25) 1.3

by running the following modification to PasswordDemo 反对 h2数据库:

if (isPasswordCorrect(input)) {
    try {
        Connection conn = DriverManager.getConnection(
            "jdbc:h2:mem:", "sa", "secret");
        DatabaseMetaData metaData = conn.getMetaData();
        System.out.println("Version:"
            + " " + metaData.getDatabaseProductName()
            + " " + metaData.getDatabaseProductVersion()
            + " " + metaData.getDatabaseMajorVersion()
            + "." + metaData.getDatabaseMinorVersion());
    } catch (SQLException ex) {
        ex.printStackTrace(System.err);
    }
} ...

附录:我得到以下结果,

Version: Apache Derby 10.6.2.1 - (999685) 10.6

by running the following modification to PasswordDemo 反对 apache derby :

if (isPasswordCorrect(input)) {
    try {
        EmbeddedDataSource ds = new EmbeddedDataSource();
        ds.setDatabaseName("/home/trashgod/.netbeans-derby/dbtest");
        Connection conn = ds.getConnection("sa", "secret");
        DatabaseMetaData metaData = conn.getMetaData();
        System.out.println("Version:"
            + " " + metaData.getDatabaseProductName()
            + " " + metaData.getDatabaseProductVersion()
            + " " + metaData.getDatabaseMajorVersion()
            + "." + metaData.getDatabaseMinorVersion());
    } catch (SQLException ex) {
        ex.printStackTrace(System.err);
    }
} ...

其他推荐答案

我终于开始工作了!我有另一个具有相同变量名称的构造函数,我对JTEXTFIELD的呼叫被误认为是对另一个构造函数的呼叫. Foo陈述确实有帮助!!!谢谢大家!

本文地址:https://www.itbaoku.cn/post/597373.html

问题描述

It's me again and I just can't seem to get this code to work. I'm basically asking for any advice on why the button does nothing when clicked. Would you like me to attach the source code?

The method I'm trying to implement:

   public static void UserInput() {
      try {
         stmt = connect.createStatement();
         ResultSet res = stmt.executeQuery("SELECT * FROM " + tableName);
         while (res.next()) {
            if (res.getString("Username").equals(usernameField.getText())) {
               if (res.getString("Password").equals(passwordField.getPassword())) {
                  JOptionPane.showMessageDialog(null, "Correct", "Correct",
                           JOptionPane.INFORMATION_MESSAGE);
               } else {
                  JOptionPane.showMessageDialog(null, "Error. Incorrect "
                           + "username or password.", "Error",
                           JOptionPane.ERROR_MESSAGE);
               }
            } else {
               JOptionPane.showMessageDialog(null, "Error. Incorrect "
                        + "username or password.", "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
         }
         res.close();
         stmt.close();
         connect.close();

      } catch (SQLException sqlExcept) {
         sqlExcept.printStackTrace();
      }

   }

And here's how I'm calling it:

             if(firstTime == false) {
              JavaDB jdb = new JavaDB();
         }

        JavaDB window = new JavaDB("");
        window.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                    System.exit(0);
                }
            });
        }

And here's the actionListner:

            submit = new JButton("Submit");
            c.add(submit);
              submit.addActionListener( new ActionListener() {  
                    public void actionPerformed( ActionEvent e ) { 
                      if(e.getSource().equals(submit)) {
                         UserInput();
            }
         }  
     });  ;        

If you need anymore let me know. I've been teaching myself Java and I don't really know what to learn so any tips will be welcomed. I'm also new to stack overflow and posting code so any thing you can give me will be more than appreciated. Thanks in advance.

Edit: I now added a class for event handling with the Thread inside of it like this;

             public class ButtonHandler implements ActionListener{
    public void actionPerformed(ActionEvent e){
        if(e.getSource().equals(submit)){
            Thread th = new Thread(new JavaDB());
            th.start();
            th.run();
            try {
                th.wait();
            } catch (InterruptedException e1) {
            }
        }
        else{
        System.exit(0);
        }   
    }

And I changed UserInput to run(). However,now when I click the submit button,The GUI disappears. Just for a reference you might need, here's my main method:

             public static void main(String args[]) throws SQLException,
        InterruptedException {
    createConnection();
    boolean firstTime = firstTime();
    if (firstTime) {
        JavaDB db = new JavaDB("");
        db.createAccount();
        try {
            connect = DriverManager
                    .getConnection("jdbc:derby:\\KeithDB;shutdown=true");
        } catch (SQLException XJ015) {
        }
    }
    if (firstTime == false) {
        JavaDB jdb = new JavaDB();
        Thread th = new Thread();
    }

    JavaDB window = new JavaDB("");
    window.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
}

Anything else you need,let me know

推荐答案

PasswordDemo, as shown in How to Use Password Fields, would be a good starting point for your study, and it would make an effective sscce.

Addendum: Absent a complete example or knowledge of what database you are using, I got the following result,

Version: H2 1.3.157 (2011-06-25) 1.3

by running the following modification to PasswordDemo against H2 Database:

if (isPasswordCorrect(input)) {
    try {
        Connection conn = DriverManager.getConnection(
            "jdbc:h2:mem:", "sa", "secret");
        DatabaseMetaData metaData = conn.getMetaData();
        System.out.println("Version:"
            + " " + metaData.getDatabaseProductName()
            + " " + metaData.getDatabaseProductVersion()
            + " " + metaData.getDatabaseMajorVersion()
            + "." + metaData.getDatabaseMinorVersion());
    } catch (SQLException ex) {
        ex.printStackTrace(System.err);
    }
} ...

Addendum: I got the following result,

Version: Apache Derby 10.6.2.1 - (999685) 10.6

by running the following modification to PasswordDemo against Apache Derby:

if (isPasswordCorrect(input)) {
    try {
        EmbeddedDataSource ds = new EmbeddedDataSource();
        ds.setDatabaseName("/home/trashgod/.netbeans-derby/dbtest");
        Connection conn = ds.getConnection("sa", "secret");
        DatabaseMetaData metaData = conn.getMetaData();
        System.out.println("Version:"
            + " " + metaData.getDatabaseProductName()
            + " " + metaData.getDatabaseProductVersion()
            + " " + metaData.getDatabaseMajorVersion()
            + "." + metaData.getDatabaseMinorVersion());
    } catch (SQLException ex) {
        ex.printStackTrace(System.err);
    }
} ...

其他推荐答案

I finally got it to work! I had another constructor with the same variable names and my call to the JTextFields were mistaken to be the call to the other constructor. The foo statements really helped!!! Thank you everyone!