Som Adhikari Som Adhikari - 4 months ago 10
Java Question

How to take value of JTextfield declared in main function from outside of main function?

I've declared text field as:

public class ContactInformation implements ActionListener {
private JTextField finame;
private JTextField laname;
private JTextField dist;
private JTextField cty;

public static void main(String [] args) throws Exception{
JTextField fname = new JTextField(20);
JTextField lname = new JTextField(20);
JTextField district = new JTextField(20);
JTextField city = new JTextField(20);
}

public void insertUser(){
try {
contains = DriverManager.getConnection("jdbc:mysql://localhost:3306/contact_info","root","");
System.out.println("Connection established");
stmt = contains.prepareStatement(insertUser);
stmt.setString(1,a);
stmt.setString(2,b);
int rowinserted = stmt.executeUpdate();
if (rowinserted>0){
System.out.println("Inserted successfully!!!");
}
}
}


So, my program structure is like above. In this code I have to take value from text box into
stmt.setString(1,a);
[in the field a there should be value of text field].

How I get value from text box to
a
?

Answer

If you want to have the value of your JTextField "finame" as a, you must write:

stmt.setString(1, finame.getText());

Also your creating new JTextFields in your main, not the ones you declared in your class! You must create an constructor and create them in it: Correct:

public static void ContactInformation(String [] args) throws Exception{
    finame = new JTextField(20);
    laname = new JTextField(20);
    dist = new JTextField(20);
    cty = new JTextField(20);
}

Notice the missing "JTextField" and the corrected names.

In your main-Method you have to call that constructor:

public static void main(String [] args) throws Exception{
    ContactInformation contactInformation = new ContactInformation();
    //TODO work with contactInformation
}
Comments