简体   繁体   中英

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. 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.

In the JFrame ( ecframe.java ) have i created a textfield and a button. When typing in the email address and pressing the button it will store this information to a string called textFieldValue. But what i can't figure out is how to get this string into my ec.java file.

This is my code from 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 :

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

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

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.

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

You need to provide some way so that the ec class can expose its functionality...

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...

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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