简体   繁体   English

从JFrame到Java类获取字符串值

[英]Get string value from JFrame to a Java Class

Hello i'm trying to build a small application that will allow me to store email addresses in a MySQL database. 您好,我正在尝试构建一个小型应用程序,该应用程序允许我将电子邮件地址存储在MySQL数据库中。 What i've done is that i've created a Java Class file ( ec.java ) and a connection that works fine and code for executing this into the database. 我所做的是创建了一个Java类文件( ec.java )和一个运行良好的连接以及将其执行到数据库中的代码。

In the JFrame ( ecframe.java ) have i created a textfield and a button. 在JFrame( ecframe.java )中,我创建了一个文本字段和一个按钮。 When typing in the email address and pressing the button it will store this information to a string called textFieldValue. 在输入电子邮件地址并按下按钮时,它将把此信息存储到一个名为textFieldValue的字符串中。 But what i can't figure out is how to get this string into my ec.java file. 但是我不知道是如何将此字符串放入我的ec.java文件中。

This is my code from ec.java: 这是我来自 ec.java的 代码

package emailcollector;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;


public class ec {

    public static void main(String[] args) {
        try{
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost", "admin", "pass");

            Statement stmt = (Statement) con.createStatement();

            String email = textFieldValue;

            String insert = "INSERT INTO emails VALUES ('" + email + ")";

            stmt.executeUpdate(insert);
        }catch(Exception e) {
    }
    }
}

And this is my code inside the ecframe.java : 这是我在 ecframe.java中的 代码

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        String textFieldValue = jTextField1.getText();

        JOptionPane.showMessageDialog(this, "Added: \nEmail: " + textFieldValue);
    } 

Is this because of the "private". 是因为“私人”。 It's confusing for me. 这让我感到困惑。 Thanks in advance! 提前致谢!

make con static variable in ec.java, then on ecframe on button action event call the mysql statement, and create the statement by calling the static connection con variable 在ec.java中创建con静态变量,然后在ecframe上的按钮操作事件上调用mysql语句,并通过调用静态连接con变量来创建该语句

package emailcollector;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;


public class ec {

    public static Connection con;
    public static void main(String[] args) {
        try{
            con = DriverManager.getConnection("jdbc:mysql://localhost", "admin", "pass");


        }catch(Exception e) {
    }
    }
}

ecframe.java ecframe.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            String textFieldValue = jTextField1.getText();

        Statement stmt = (Statement) ec.con.createStatement();

            String email = textFieldValue;

            String insert = "INSERT INTO emails VALUES ('" + email + ")";

            stmt.executeUpdate(insert);
    } 

Instead of making things static, often times I like to make my components independent of one another. 经常使我的组件彼此独立,而不是使它们静态化。 In particular, I like the way that JFileChooser and JColorChooser work, so I like to emulate their functionality here by using either a modal JDialog, or a JOptionPane. 特别是,我喜欢JFileChooser和JColorChooser的工作方式,因此我喜欢在这里通过使用模式JDialog或JOptionPane来模拟其功能。

For example, here's a simple panel that represents a form that takes an email: 例如,这是一个简单的面板,代表接收电子邮件的表单:

class EmailForm extends JPanel {
    private JTextField emailField = new JTextField(20);

    public EmailForm() {
        add(new JLabel("Email"));
        add(emailField);
    }

    public String getEmail() {
        return emailField.getText();
    }
}

And in your main method, you'd simply say: 在您的主要方法中,您只需说:

EmailForm form = new EmailForm();
int option = JOptionPane.showConfirmDialog(null, form, "Email", JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
    System.out.println(form.getEmail());
}

Now, if in your case the form can't be made independent, and the class that holds that database connection represents a context without which the UI cannot function properly, then you might want to occasionally pass a dependency like that to the main form's constructor. 现在,如果您不能将表单做成独立的,并且拥有该数据库连接的类表示一个上下文,那么UI无法正常运行,那么您可能希望偶尔将类似的依赖项传递给主表单的构造函数。 Other than that, you can fiddle with actions, event listeners, or even the factory pattern as others have suggested. 除此之外,您还可以摆弄动作,事件侦听器甚至其他人建议的工厂模式。

There are a number of ways you could achieve this, this is just one (and it's a start of a very BASIC example of a possible Factory pattern) 您可以通过多种方式实现这一目标,但这只是其中的一种(这是可能的Factory模式的非常基本的示例的开始)

You need to provide some way so that the ec class can expose its functionality... 您需要提供某种方式,以便ec类可以公开其功能...

Something more like... 更像是...

public class EmailManager {

    private Connection con;

    protected Connection getConnection() {
        if (connection == null) {
            con = DriverManager.getConnection("jdbc:mysql://localhost", "admin", "pass");
        }
        return con;
    }

    public void close() throws SQLException {
        if (con != null) {
            con.close();
        }
        con = null;
    }

    public void insertEmail(String email) throws SQLException {
        Statement stmt = null;
        try {
            Statement stmt = getConnection().createStatement();
            int count = stmt.execute("insert into emails values ('" + email + "')");
            if (count != 1) {
                throw new SQLException("Failed to insert new email");
            }
        } finally {
            try {
                stmt.close();
            } catch (Exception exp) {
            }
        }
    }
}

Then in your UI class, you simple create an instance of ec and access it's methods as required... 然后在您的UI类中,您简单地创建ec的实例并根据需要访问其方法...

private EmailManager manager;

/*...*/

protected EmailManager getEMailManager() {
    if (manager == null) {
        manager = new EmailManager();
    }
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String textFieldValue = jTextField1.getText();
    try {
        getEMailManager().insertEmail(textFieldValue);
    } catch (SQLException exp) {
        JOptionPane.showMessageDialog(this, "Failed to insert email into database", "Error", JOptionPane.ERROR_MESSAGE);
        exp.printStackTrace();
    }
} 

No offense, but all of this is basic OO programming. 没有冒犯,但是所有这些都是基本的OO编程。 You might like to take a read through Classes and Objects for more details and ideas 您可能想通读类和对象以了解更多详细信息和想法

You may also like to take a look at Code Conventions for the Java Programming Language 您可能还想看看Java编程语言的代码约定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM