Java - 来自 JFrame 控件的变量

Posted

技术标签:

【中文标题】Java - 来自 JFrame 控件的变量【英文标题】:Java - Variables from JFrame Controls 【发布时间】:2015-02-28 05:26:39 【问题描述】:

我对 Java 比较陌生,而且我是自学的。目前我正在尝试开发一个包含文本字段和按钮的框架。该按钮在我的个人数据库中运行 SQL 查询,我希望 WHERE 子句使用文本字段中的文本填充。但是我无法将 txtField.getText() 值传递给构建 SQL 语句的类。它不会抓取在该字段中输入的内容,而是只给我该字段的默认文本。

我希望有人可以查看我的代码(如下)并告诉我哪里出错了。当我在 SQL 类中创建一个新的 Frame1 对象时,我有一种感觉,但我无法理解这个问题。

框架类的代码:

    public Frame1() 
        initComponents();
    


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() 

        jLabel2 = new javax.swing.JLabel();
        stateCodeVar = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        lblStateCodeVar = new javax.swing.JLabel();
        txtDestVar = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel2.setText("Enter the state abbreviation:");

        stateCodeVar.setName("txtState"); // NOI18N
        stateCodeVar.addFocusListener(new java.awt.event.FocusAdapter() 
            public void focusLost(java.awt.event.FocusEvent evt) 
                stateCodeVarFocusLost(evt);
            
        );

        jButton1.setText("Search");
        jButton1.setName("btnSearch"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() 
            public void actionPerformed(java.awt.event.ActionEvent evt) 
                jButton1ActionPerformed(evt);
            
        );

        lblStateCodeVar.setText("jLabel1");
        lblStateCodeVar.setName("lblStateCodeVar"); // NOI18N

        txtDestVar.setText("jTextField1");
        txtDestVar.setName("txtDest"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(44, 44, 44)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(stateCodeVar, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(149, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtDestVar, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblStateCodeVar))
                .addGap(63, 63, 63))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(13, 13, 13)
                .addComponent(lblStateCodeVar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(stateCodeVar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 70, Short.MAX_VALUE)
                .addComponent(txtDestVar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(103, 103, 103))
        );

        pack();
    // </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)                                          

        sqlSearchByState sql1 = new sqlSearchByState();
        try 
        sql1.sqlSearch();
        System.out.println("The query is finished.");
        String code = getStateCode();
        /* System.out.println(code); */
        
        catch (SQLException e)
        e.printStackTrace();
        
                                            

    private void stateCodeVarFocusLost(java.awt.event.FocusEvent evt)                                        
        txtDestVar.setText(stateCodeVar.getText());
                                          

    public String getStateCode()
    String result = stateCodeVar.getText();
    return result;    
    

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) 
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try 
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) 
                if ("Nimbus".equals(info.getName())) 
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                
            
         catch (ClassNotFoundException ex) 
            java.util.logging.Logger.getLogger(Frame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
         catch (InstantiationException ex) 
            java.util.logging.Logger.getLogger(Frame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
         catch (IllegalAccessException ex) 
            java.util.logging.Logger.getLogger(Frame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
         catch (javax.swing.UnsupportedLookAndFeelException ex) 
            java.util.logging.Logger.getLogger(Frame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() 
            public void run() 
                new Frame1().setVisible(true);
            
        );
    

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel2;
    public javax.swing.JLabel lblStateCodeVar;
    public javax.swing.JTextField stateCodeVar;
    public javax.swing.JTextField txtDestVar;
    // End of variables declaration                   

SQL类的代码:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Eli Oklesh
 */
public class sqlSearchByState 

    public void sqlSearch() throws SQLException 
    dbCon1 dbc = new dbCon1();

    Frame1 f = new Frame1();

    f.getStateCode();
    String stateCode = f.getStateCode();

    Connection conn1;
        Statement stmt2;
        String query = "SELECT * FROM users WHERE userLocation = '" + stateCode + "'";

        conn1 = dbc.makeConnection();

        try

        stmt2 = conn1.createStatement();
        ResultSet rs = stmt2.executeQuery(query);

        if (rs.next())
            while (rs.next())
                int userID = rs.getInt("ID");
                String userFirstName = rs.getString("userFirstName");
                String userLastName= rs.getString("userLastName");
                String userLocation = rs.getString("userLocation");

                System.out.println(userID + "\t" + userFirstName + "\t" + userLastName + "\t" + userLocation);


                
            System.out.println(query);
        
        else 
        System.out.println("No records were returned.");
        System.out.println(query);

        
            
        catch (SQLException e)
            System.out.println("There was an error:" + "\t" + e);
            
        finally 
            if (conn1 != null) conn1.close();
            
        


帮助!提前致谢!

【问题讨论】:

【参考方案1】:

您正在执行查询的类中创建框架的新实例,但它不是屏幕上显示的框架,因此您尝试使用的值不是用户输入的值。

相反,您希望将帧中的值传递给正在执行 sql 的类...

    sql1.sqlSearch(txtDestVar.getText());

然后您需要更改sqlSearch 方法...

public void sqlSearch(String text) throws SQLException 

然后您需要从 sql 类中删除框架的引用,并改用 text 参数

【讨论】:

疯狂程序员 - 谢谢!这就像一个魅力。它帮助我理解处理多个类时使用的方法。【参考方案2】:

您的问题可以通过使用模态 JDialog 而不是 JFrame 来解决,我将解释原因...

当您显示 JFrame 时,它​​是非模态的,这意味着创建 JFrame 并显示它的调用代码不会停止,而是在显示 JFrame 时继续运行。 因此,如果您在创建 JFrame 后尝试立即从 JFrame 中提取信息(拍摄,我没有看到您的代码甚至显示它),那么它会在用户有机会与 JFrame 交互之前被提取,甚至可能在 JFrame 显示之前。 另一方面,模式对话框会暂停调用代码,直到对话框不再可见,这将使用户有机会与对话框窗口进行交互。 那么当您从对话框中提取信息时,很可能是在用户输入之后获得的相关信息。

【讨论】:

悬停 - 感谢您的洞察力。目前我可以说这超出了我的 Java 知识范围。但我有兴趣了解更多,因为随着我学习的进步,我想更多地了解您建议的 JDialog 解决方案。我一定会查一下..谢谢!

以上是关于Java - 来自 JFrame 控件的变量的主要内容,如果未能解决你的问题,请参考以下文章

实时监听JFrame高宽

java窗口添加背景

Java中如何设置在JFrame中控件的位置和大小

来自线程内的实例化组件不会重绘到 Java 中的 JFrame

Java中的重绘()

如何在JFrame中展示一个网页?